코딩하는 나귀

[주의사항]


코드에서 보이겠지만 MonoBehaviour의 클래스 특성상 사용자가 직접 객체를 생성하는 것이 아니라 Unity에서

GameObject에 붙일 객체를 직접 생성한다. 그러므로 Awake에 최초 인스턴스를 할당하는 코드가 들어있다

그러므로 상속받은 클래스에서는 Awake를 사용할 수 없는 문제가 있지만 같은 타이밍에 Init 함수를 오버라이드

해서 사용하면 되도록 되어있다. 당연한 이야기이지만 다른 MonoBehaviour에서 참조하는 일은 하지말도록...

객체는 생성되겠지만 GameObject에 붙어있는 객체 일지는 장담할 수 없다...



using UnityEngine;
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T m_Instance = null;
    public static T instance
    {
        get
        {
            // Instance requiered for the first time, we look for it
            if( m_Instance == null )
            {
                m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
 
                // Object not found, we create a temporary one
                if( m_Instance == null )
                {
                    Debug.LogWarning("No instance of " + typeof(T).ToString() + ", a temporary one is created.");
                    m_Instance = new GameObject("Temp Instance of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
 
                    // Problem during the creation, this should not happen
                    if( m_Instance == null )
                    {
                        Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                    }
                }
                m_Instance.Init();
            }
            return m_Instance;
        }
    }
    // If no other monobehaviour request the instance in an awake function
    // executing before this one, no need to search the object.
    private void Awake()
    {
        if( m_Instance == null )
        {
            m_Instance = this as T;
            m_Instance.Init();
        }
    }
 
    // This function is called when the instance is used the first time
    // Put all the initializations you need here, as you would do in Awake
    public virtual void Init(){}
 
    // Make sure the instance isn't referenced anymore when the user quit, just in case.
    private void OnApplicationQuit()
    {
        m_Instance = null;
    }
}

[출처:http://wiki.unity3d.com/index.php/Singleton]

'Unity' 카테고리의 다른 글

[Struct] Point  (0) 2015.11.07
[Struct] Size  (0) 2015.11.07
[Shader] 텍스처 회전 (Texture Rotation)  (0) 2015.09.08
C# 리스트(List)를 이용해 만든 우선순위큐(PriorityQueue)  (0) 2015.07.23
리플렉션 응용 (C# Reflection)  (0) 2015.07.01
MonoBehaviour Lifecycle  (0) 2014.06.30
Android Local Notification Plugin  (0) 2013.04.23
포물선 공식  (0) 2013.01.21
케릭터 점프 코드  (0) 2013.01.15
드레그한 방향 알아내기  (0) 2013.01.15