Programming/Unity

SingleTon

Inner-Peace 2017. 12. 27. 12:21
반응형

MonoBehaviour Singleton.


public class MonoBehaviourSingleton<T> : MonoBehaviour where T: MonoBehaviour {


    protected bool isDonDestroy = false;

    

    void Awake()

    {

        if (isDonDestroy)

        {

            DontDestroyOnLoad(this.gameObject);

        }

    }


    private static T instance;

    public static T Instance

    {

        get

        {

            if (instance == null)

            {

                T[] objs = FindObjectsOfType<T>();


                if (objs.Length > 0)

                {

                    instance = objs[0]; 

                }


                if (instance == null)

                {

                    string name = typeof(T).ToString();

                    GameObject go = GameObject.Find(name);

                    if (go == null)

                    {

                        go = new GameObject(name);

                    }

                    instance = go.AddComponent<T>();

                }

            }


            return instance;

        }

    }

}


Class Singleton

Reflection을 통해 생성자 확인.

public class Singleton<T> where T: class {


    private static T instance = null;

    public static T Instance

    { 

        get

        {

            if (instance == null)

            {

                Type t = typeof(T);


                ConstructorInfo[] ctors = t.GetConstructors();

                if (ctors.Length > 0)   // if there are public constructors, it's error.

                {

                    throw new InvalidOperationException(string.Format("Error : Have public constructor"));

                }


                instance = (T)Activator.CreateInstance(t, true);

            }


            return instance;

        }

    }

}


반응형