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

카테고리

분류 전체보기 (2077)
Unity3D (462)
Programming (453)
Unreal (2)
Gamebryo (56)
Tip & Tech (157)
협업 (23)
3DS Max (3)
Game (12)
Utility (97)
Etc (86)
Link (29)
Portfolio (18)
Subject (90)
iPhone (30)
Android (2)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (1)
Memories (16)
Interest (36)
Thinking (29)
한글 (23)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (14)
Exercise (3)
나만의 맛집 (2)
냥이 (7)
육아 (2)
Total1,058,849
Today6
Yesterday214
Statistics Graph

달력

« » 2017.06
        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  

공지사항

태그목록

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

'Singleton'에 해당되는 글 7건

  1. 2014.03.24 Unity Singleton
  2. 2014.03.05 Generic Based Singleton for MonoBehaviours完全版(?)
  3. 2014.03.05 Singleton
  4. 2013.03.11 Unity Singleton
  5. 2010.10.22 C++/CLI Singleton
  6. 2010.07.02 C# 싱글톤
  7. 2010.07.02 Singleton

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

댓글을 달아 주세요

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using UnityEngine;
 
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    static T m_Instance = null;
 
    public static T instance
    {
        get
        {
            if( m_Instance != null )
            {
                return m_Instance;
            }
 
            System.Type type = typeof(T);
 
            T instance = GameObject.FindObjectOfType(type) as T;
 
            if( instance == null )
            {
                string typeName = type.ToString();
 
                GameObject gameObject = new GameObject( typeName, type );
                instance = gameObject.GetComponent<T>();
 
                if( instance == null )
                {
                    Debug.LogError("Problem during the creation of " + typeName,gameObject );
                }
            }
            else
            {
                Initialize(instance);
            }
            return m_Instance;
        }
    }
 
    static void Initialize(T instance)
    {
        if( m_Instance == null )
        {
            m_Instance = instance;
 
            m_Instance.OnInitialize();
        }
        else if( m_Instance != instance )
        {
            DestroyImmediate( instance.gameObject );
        }
    }
 
    static void Destroyed(T instance)
    {
        if( m_Instance == instance )
        {
            m_Instance.OnFinalize();
 
            m_Instance = null;
        }
    }
 
    public virtual void OnInitialize() {}
    public virtual void OnFinalize() {}
 
    void Awake()
    {
        Initialize( this as T );
    }
 
    void OnDestroy()
    {
        Destroyed( this as T );
    }
 
    void OnApplicationQuit()
    {
        Destroyed( this as T );
    }
}

使い方は

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using UnityEngine;
using System.Collections;
 
public class TestSingleton : MonoSingleton<TestSingleton>
{
    public override void OnInitialize()
    {
        Debug.Log ( "TestSingleton#OnInitialize" );
    }
 
    public override void OnFinalize()
    {
        Debug.Log ( "TestSingleton#OnFinalize" );
    }
}


출처 : http://caitsithware.com/wordpress/?p=118

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

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

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
Serializable, NonSerialized  (0) 2013.07.30
Get MAC address on Android device  (0) 2013.07.24
Posted by blueasa
TAG Singleton

댓글을 달아 주세요

Singleton

Unity3D/Script / 2014.03.05 10:41

일반형 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MySingleton
{
    private static MySingleton instance;
 
    //
    private MySingleton()
    {
 
    }
 
    static MySingleton()
    {
        instance = new MySingleton();
    }
 
    public static MySingleton Instance
    {
        get
        {
            return instance;
        }
    }
};

Component용 Singleton

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
32
33
34
35
36
37
38
39
40
41
42
43
44
using UnityEngine;
using System.Collections;
 
public class MySingleton : MonoBehaviour {
 
    private static MySingleton instance;
     
    //
    private MySingleton()
    {
    }
     
    //
    public static MySingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance =  FindObjectOfType(typeof (MySingleton)) as MySingleton;
             
                if (instance == null)
                {
                    GameObject obj = new GameObject("MySingleton");
                    instance = obj.AddComponent(typeof (MySingleton)) as MySingleton;
                    Debug.Log ("Could not locate an MySingleton object. MySingleton was Generated Automaticly.");
                }
            }
  
            return instance;
        }
    }
     
    void Awake()
    {
        DontDestroyOnLoad(this);
    }
     
    void OnApplicationQuit()
    {
        instance = null;
    }
}

제네릭 버전

일반형 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class  Singleton<T> where T : class, new()
{
    private static T instance;
         
    static Singleton()
    {
        instance = new T();
    }
     
    public static T Instance
    {
        get
        {
            return instance;
        }
    }
};

Component용 Singleton

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using UnityEngine;
using System.Collections;
  
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T instance;
     
    //
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance =  FindObjectOfType(typeof(T)) as T;
             
                if (instance == null)
                {
                    GameObject obj = new GameObject(typeof (T).ToString());
                    instance = obj.AddComponent(typeof (T)) as T;
                    instance.Init();
         
                    Debug.Log ("Could not locate an " + typeof (T).ToString() +" object. " + typeof (T).ToString() + " was Generated Automaticly.");
                }
            }
         
            return instance;
        }
    }
      
    void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            instance.Init();
        }
         
        DontDestroyOnLoad(this);
    }
      
    void OnApplicationQuit()
    {
        instance = null;
    }
     
    public virtual void Init()
    {
         
    }