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 | // Singleton<T>.cs using UnityEngine; using System.Collections; public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { private static T _singleton; private static object _lock = new object(); private static bool appIsQuitting = false; public static T singleton { get { if (appIsQuitting) { Debug.LogError("[Singleton<" + typeof(T).ToString() + ">] : " + "already destroyed on application quit"); return null; } lock (_lock) { if (_singleton == null) { _singleton = FindObjectOfType<T>(); if (FindObjectsOfType(typeof(T)).Length > 1) { Debug.LogError("[Singleton<" + typeof(T).ToString() + ">] : " + "singleton instance is duplicated"); return _singleton; } if (_singleton == null) { GameObject go = new GameObject(); _singleton = go.AddComponent<T>(); _singleton.name = typeof(T).ToString(); DontDestroyOnLoad(_singleton); } } return _singleton; } } } public virtual void OnApplicationQuit () { appIsQuitting = true; _singleton = null; } } | cs |
1 2 3 4 5 6 7 8 | // Example - GameManager.cs public class GameManager : Singleton<GameManager> { protected GameManager () { // guarentee this object will be always a singleton only - can not use the constructor } } | cs |
1 2 3 4 5 6 7 8 9 10 11 | // Example - Main.cs using UnityEngine; using System.Collections; public class Main : MonoBehaviour { void Awake () { Debug.Log(GameManager.singleton.GetType().ToString()); } } | cs |
'02.Development > Design Pattern' 카테고리의 다른 글
[DesignPattern] Observer Pattern (C#) (0) | 2016.03.15 |
---|