본문 바로가기
Unity3D/Unity & C#

Unity & C# ~ Singleton(싱글톤)

by 캬캬백곰 2022. 5. 20.
728x90
//예제1
private static T _instance = null;

    public static T _Instance
    {
        get 
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType(typeof(T)) as T;
            }                

            return _instance; 
        }
    }
    
//예제2
private static T _instance = null;

    public static T _Instance
    {
        get 
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType(typeof(T)) as T;

                if (_instance == null)
                {
                    GameObject obj = new GameObject();
                    obj.name = "NAME";

                    _instance = obj.AddComponent<T>();
                }
            }

            return _instance; 
        }
    }
    
//예제3
public class Singleton<T> where T : class, new()
{
	public static readonly T Instance = new T();
}

//예제4
public class Singleton<T> where T : class, new()
{
    private static T _instance;
    
    public static T Instance 
    { 
    	get 
        { 
        	if (_instance == null) 
            	_instance = new T(); 
                
            return _instance; 
        } 
    }

    public virtual void Init() { }

    public static void SetInstance(T instance) 
    { 
    	_instance = instance; 
    }
}
728x90
반응형