Generic Based Singleton for MonoBehaviours完全版(?)
Unity3D/Script / 2014. 3. 5. 10:43
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" ); } } |
반응형
'Unity3D > Script' 카테고리의 다른 글
Unity Singleton (0) | 2014.03.24 |
---|---|
Platform Dependent Compilation (0) | 2014.03.11 |
Singleton (0) | 2014.03.05 |
Serializable, NonSerialized (0) | 2013.07.30 |
Get MAC address on Android device (0) | 2013.07.24 |