블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2128)
Unity3D (482)
Programming (455)
Unreal (2)
Gamebryo (56)
Tip & Tech (164)
협업 (28)
3DS Max (3)
Game (12)
Utility (101)
Etc (90)
Link (29)
Portfolio (19)
Subject (90)
iPhone (31)
Android (2)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (1)
Memories (16)
Interest (36)
Thinking (34)
한글 (23)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (16)
Exercise (3)
나만의 맛집 (2)
냥이 (7)
육아 (2)
Total1,119,890
Today36
Yesterday204
Statistics Graph

달력

« » 2017.12
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

공지사항

태그목록

Tistory Cumulus Flash tag cloud by BLUEnLIVE requires Flash Player 9 or better.

Unity Singleton

Unity3D/Script / 2014.03.24 18:36
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    protected static bool m_bDontDestroyOnLoad = true;
    
    private static bool m_bApplicationQuit = false;
    private static object InstanceLocker = new object();

    private static T m_Instance = null;
    public static T Instance
    {
        get
        {
            if (true == m_bApplicationQuit)
                return null;

            lock (InstanceLocker)
            {
                // Instance requiered for the first time, we look for it
                if (null == m_Instance)
                {
                    T instance = GameObject.FindObjectOfType(typeof(T)) as T;

                    // Object not found, we create a temporary one
                    if (instance == null)
                    {
                        instance = new GameObject(typeof(T).ToString()).AddComponent<T>();

                        // Problem during the creation, this should not happen
                        if (instance == null)
                        {
                            Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                        }
                    }

                    if (instance != null)
                    {
                        Initialize(instance);
                    }
                }

                return m_Instance;
            }
        }
    }

    private static void Initialize(T instance)
    {
        if (m_Instance == null)
        {
            var startTime = System.DateTime.Now;
            m_Instance = instance;

            // 씬 전환 시, 삭제시킬 싱글톤은 부모 객체에 안붙이도록..
            // 싱글톤 시작 시, m_bDontDestroyOnLoad 셋팅 필요.
            if (true == m_bDontDestroyOnLoad)
            {
                GameObject goRoot = GameObject.Find("Singletons") as GameObject;
                if (null == goRoot)
                {
                    goRoot = new GameObject("Singletons");
                    // DontDestroyOnLoad() 등록은 하위 상속받는 쪽에서 하도록 하는 게 나을까?
                    DontDestroyOnLoad(goRoot);
                }
                m_Instance.transform.parent = goRoot.transform;
            }

            m_Instance.OnInitialize();
            var period = System.DateTime.Now - startTime;
            if (period.TotalSeconds > 1.0f)
            {
                var name = m_Instance.ToString();
                Debug.LogWarning("Profile Warnning. Singletion {" + name + "} too long init time : " 
                                 + period.TotalSeconds.ToString("F") + "Seconds");
            }
        }
        else if (m_Instance != instance)
        {
            DestroyImmediate(instance.gameObject);
        }
    }

    private static void Destroyed(T instance)
    {
        if (m_Instance == instance)
        {
            m_Instance.OnFinalize();
            m_Instance = null;
        }
    }

    public void CreateSingleton() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnInitialize() 호출 안됨.
    public virtual void OnInitialize() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnFinalize() 호출 안됨.
    public virtual void OnFinalize() { }
    protected virtual void CheckDontDestroyOnLoad() { }

    private void Awake()
    {
        Initialize(this as T);
    }

    void OnDestroy()
    {
        Destroyed(this as T);
    }

    private void OnApplicationQuit()
    {
        m_bApplicationQuit = true;
        Destroyed(this as T);
    }
}


저작자 표시 비영리 동일 조건 변경 허락
신고

'Unity3D > Script' 카테고리의 다른 글

A simple cross fade shader for Unity  (0) 2014.04.22
어플을 내렸을때, 어플을 종료할때의 처리  (3) 2014.04.04
Unity Singleton  (0) 2014.03.24
Platform Dependent Compilation  (0) 2014.03.11
Generic Based Singleton for MonoBehaviours完全版(?)  (0) 2014.03.05
Singleton  (0) 2014.03.05
Posted by blueasa

댓글을 달아 주세요