검색결과 리스트
글
Unity3D에서의 싱글톤 구현
Programming/Unity3D
2014. 6. 8. 18:11
//컴포넌트 기반 싱글톤 //------------------------------------------------------------------------------------------- using UnityEngine; public class MySingleton : MonoBehaviour { private static MySingleton instance; public static MySingleton Instance { get { if ( instance == null ) instance = new GameObject("MySingleton").AddComponent출처 : http://blog.naver.com/rapha0/110154460575( ); return instance; } } public void OnApplicationQuit( ) { instance = null; } } //------------------------------------------------------------------------------------------- //사용 예) public class MySingleton { private static MySingleton instance; // 인스턴스 public MySingleton( ) { if ( instance != null ) { Debug.LogError( "Can't have two instances of singleton !!" ); return; } instance = this; } public static MySingleton Instance { get { if ( instance == null ) new MySingleton( ); //첫 인스턴스 생성 return instance; } } private int score; // 내부 데이터 변수 public int Score { get { return scroe; } set { score = value; } } } //------------------------------------------------------------------------------------------- MySingleton.Instance.Score += 9; Debug.Log( "Score is now: " + MySingleton.Instance.Score ); //템플릿 기반 싱글톤 //------------------------------------------------------------------------------------------- using UnityEngine; public abstract class MonoSingleton< T > : MonoBehaviour where T : MonoSingleton< T > { private static T m_Instance = null; public static T instance { get { if ( m_Instance == null ) { m_Instance = GameObject.FindObjectOfType( typeof(T) ) as T; if ( m_Instance == null) Debug.LogError( "No instance of " + typeof(T).ToString( ) ); m_Instance.Init( ); } return m_Instance; } } private void Awake( ) { if ( m_Instance == null ) { m_Instance = this as T; m_Instance.Init( ); } } public virtual void Init( ) { } // 초기화를 상속을 통해 구현 private void OnApplicationQuit( ) { m_Instance = null; } } //------------------------------------------------------------------------------------------- //사용 예) GameManager.cs public class GameManager : MonoSingleton< GameManager > { public int difficulty = 0; public override void Init( ) { difficulty = 5; } } //------------------------------------------------------------------------------------------- OtherClass.cs using UnityEngine; public class OtherClass : MonoBehaviour { void Start( ) { print( GameManager.instance.difficulty ); } }
'Programming > Unity3D' 카테고리의 다른 글
Unity3D에서 Visual Studio 2013 사용하기 (0) | 2014.06.07 |
---|