Unity Singleton 单例
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 |
using UnityEngine; using System.Collections; abstract public class Singleton<T> : MonoBehaviour where T : Singleton<T> { private static T m_instance = null; public static T instance { get { if (m_instance == null) { Object go = GameObject.FindObjectOfType(typeof(T)); if (go != null) { m_instance = go as T; } if (m_instance == null) { GameObject obj = new GameObject("_" + typeof(T).FullName); m_instance = obj.AddComponent(typeof(T)) as T; } } return m_instance; } } protected virtual void Awake() { if (m_instance == null) { m_instance = this as T; } else if (m_instance != this) { Debug.LogError(" multi-singleton in scene!!! ", gameObject); gameObject.SetActive(false); } } } |
使用方式: (调用DemoSingleton.instance) Continue reading Unity Singleton 单例