유니티 싱글톤

유니티 C# 2017. 6. 7. 07:00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T instance = null;
    public static T GetInstance
    {
        get
        {
            if(instance == null)
            {
                instance = FindObjectOfType(typeof(T)) as T;
                
                if(instance == null)
                {
                    Debug.Log("Nothing" + instance.ToString());
                    return null;
                }
            }
        
            return instance;
        }
    }
}
cs


만약에 씬이 변환 되어도 파괴되지 않은 싱글톤을 만들고 싶을 때에는 상속받은 클래스의 awake 함수에 아래와 같이 선언한다.


1
DontDestroyOnLoad(this.gameObject);
cs


참고한곳: http://vallista.tistory.com/entry/Unity3D-Singleton-%EC%8B%B1%EA%B8%80%ED%86%A4