IT는 개발자

unity 싱글톤을 활용한 코드 작성하기 본문

unity

unity 싱글톤을 활용한 코드 작성하기

뚜둔64 2019. 11. 19. 13:51

🍓싱글턴(Singleton) 디자인 패턴

싱글톤 오브젝트 -> 게임 매니저, 오디오 매니저, 데이터 매니저 등 유일한 독립체로 존재하는 오브젝트

1. 클래스의 인스턴스가 하나만 생성됨을 보장
2. 어디서든지 그 인스턴스에 접근이 가능
3. 많은 싱글턴 오브젝트는 여러씬에 걸쳐 유지된다

static의 개념을 응용해서 만들어진 것이다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Test:MonoBehaviour
{
    public static Test test = null;
    private void Awake()
    {
        if(test == null)
           test = this;
        else
            Destroy(this);
    }
    void Start()
    {
        DontDestroyOnLoad(this);
    }
}
 
//unity 싱글톤 작성 방법

 

 

 

✨다른 gameObject는 Destroy 시키고 사용한다

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton : MonoBehaviour {
    public static Singleton instance;
 
    void Awake()
    {
        if ( instance )
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
 
 
✨ GameObject를 하나만 만들고 싶을 때 Awake()가 아닌 곳에서 사용한다.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class GameManager : MonoBehaviour
{
    private static GameManager instance;
    public static GameManager Instance
    {
        get
        {
            if(instance == null)
            {
                GameObject tempGM = new GameObject("GameManager");
                instance = tempGM.AddComponent<GameManager>();
                DontDestroyOnLoad(tempGM);
            }
            return instance;
        }
    }
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
cs

출처 : 

https://www.inflearn.com/course/%EC%9C%A0%EB%8B%88%ED%8B%B0-%EC%8B%AC%ED%99%94-%EA%B3%BC%EC%A0%95/lecture/10063

'unity' 카테고리의 다른 글

unity 이벤트 함수  (0) 2020.01.20
unity canvas 사이즈 조정  (0) 2020.01.20
unity 기본 개념 정리  (0) 2020.01.16
unity 화살 생성하기  (0) 2019.11.19
unity 이미지 게이지 관련 바(에너지 채우기)  (0) 2019.11.19
Comments