Unity Singleton
Unity3D/Script / 2013. 3. 11. 10:58
Example :
GameMaster.cs
public class GameMaster : MonoSingleton< GameMaster > { public int difficulty = 0; public override void Init(){ difficulty = 5; } }
OtherClass.cs
You forgot a "using UnityEngine;" fixed. :P
using UnityEngine; public class OtherClass: MonoBehaviour { void Start(){ print( GameMaster.instance.difficulty ); } // 5 }
The code :
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; } }
반응형
'Unity3D > Script' 카테고리의 다른 글
Unity3D MonoBehaviour Lifecycle(흐름도) (0) | 2013.07.03 |
---|---|
Assetbundle 을 이용한 업데이트 시스템 (0) | 2013.06.25 |
NavMesh 사용하면서 오브젝트가 밀리지 않아야 될 때.. (0) | 2013.02.13 |
Disable warning messages (0) | 2013.02.06 |
새로운 창으로 카메라 뷰어 만들기 (0) | 2013.02.05 |