Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 문자열
- dp
- 스티커 C++
- 너비우선탐색
- 프로그래머스C#
- 파라메트릭 서치
- 코딩테스트
- BFS
- 9095 C++
- C#
- 수치해석
- 이분탐색
- horner algorithm
- 프로그래머스 c#
- C
- 확률
- 통계
- 입출력
- 통계학
- C++
- 프로그래머스
- 백준
- horner
- 백준 9465
- 선형대수학
- 알고리즘
- 백준 C#
- cpp
- 확률론
- 철자검사
Archives
- Today
- Total
HOIT_B
[ 디자인패턴 ] Singleton 본문
728x90
싱글톤은 한개의 클래스 인스턴스만을 가지도록 보장하고, 이에 대한 전역적인 접근을 제공하는 디자인패턴이다.
예를들어 Player스크립트에서 @Manager객체의 manager스크립트에 접근하기 위해서 아래같은 코드를 사용할 수 있다.
GameObject go = GameObject.Find("@Manager");
Manager mg = go.GetComponent<Manager>();
하지만 게임 오브젝트를 이름으로 찾는것은 부하가 심하기 때문에 자주 사용하는 것을 지양해야한다.
아래는 싱글톤을 구현한 코드들이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager : MonoBehaviour
{
public static Manager Instance; //staic특성으로 유일성 보장
public static Manager GetInstace()
{
Init();
return Instance;
}
// Start is called before the first frame update
void Start()
{
Init();
}
static void Init()
{
if (Instance == null)
{
GameObject go = GameObject.Find("@Manager"); //객체가 있는지 체크
if (go == null) //해당 객체가 없다면
{
//새로 만들어준다.
go = new GameObject
{
name = "@Manager"
};
DontDestroyOnLoad(go);
//스크립트를 붙여준다.
Instance = go.AddComponent<Manager>();
}
}
}
}
인프런 강의에서 강사님이 구현한 코드이다.
나는 보통 아래처럼 구현한다.
private static DataManager _instance;
public static DataManager Instance
{
get
{
if (_instance == null)
{
_instance = GameObject.Find("DataManager").GetComponent<DataManager>();
}
return _instance;
}
}
private void Awake()
{
if (_instance == null)
{
_instance = this;
}
else
{
Destroy(this.gameObject);
}
}
참고
인프런 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part3: 유니티 엔진
학교 다닐 때 받은 강의를 이제 본다..! 그때 본것같았는데 놀랍게도 진행률 10%였다.
728x90
Comments