코린이 부트캠프 일상

유니티 제네릭 싱글톤

게발인개발자 2023. 12. 27. 22:49

싱글톤은 객체의 인스턴스가 오직 하나인 디자인 패턴이다. 주로 게임매니저 스크립트에서 사용한다.

싱글톤이 필요한 경우가 많을 때 사용하면 유지 보수가 편하다.

 

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
	[SerializeField]
    private bool dontDestroy = true;
    private static T instance = null;
    public static T instance
    {
    	get
        {
        	if(instance ==null)
            {
            	instance = InitManager<T>();
            }
            return instance;
        }
    }
    
     protected static U InitManager<U>() where U : MonoBehaviour
    {
        GameObject go = null;
        U obj = FindObjectOfType<U>();
        if (obj == null)
        {
            go = new GameObject(typeof(U).Name);
            go.AddComponent<U>();
        }
        else
        {
            go = obj.gameObject;
        }

        DontDestroyOnLoad(go);
        return go.GetComponent<U>();
    }

    private void Awake()
    {
        if (instance == null)
        {
            if (dontDestroy)
            {
                Instance.Init();
            }
            else
            {
                instance = GetComponent<T>();
                Init();
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }