Unity泛型单例模式

来源:互联网 发布:js鞋子是什么牌子 编辑:程序博客网 时间:2024/06/07 10:15

Unity泛型单例模式

这是单例模式代码:

这个不用挂在场景里 其实也挂不进去

using UnityEngine;using System.Collections;public class Singleton<T> : MonoBehaviour where T : Component{    private static readonly object syslock=new object();  //我叫他线程锁    private static T _instance;    public static T Instance    {        get{            if (_instance == null) {                lock (syslock) { //锁一下,避免多线程出问题                    _instance = FindObjectOfType (typeof(T)) as T;                    if (_instance == null) {                        GameObject obj = new GameObject ();                        //obj.hideFlags = HideFlags.DontSave;                        obj.hideFlags = HideFlags.HideAndDontSave;                        _instance = (T)obj.AddComponent (typeof(T));                    }                }            }            return _instance;        }    }//  这是为了不要在切换场景时单例消失,可以删掉    public virtual void Awake()    {        DontDestroyOnLoad(this.gameObject);        if(_instance == null){            _instance = this as T;        }        else{            Destroy(gameObject);        }    }    public static bool IsBuild{        get{             return  _instance != null;        }    }    // Use this for initialization    void Start () {    }    // Update is called once per frame    void Update () {    }}

这是使用代码:

我们先随便写个东西继承单例:这个不用挂在场景里 其实也挂不进去

using UnityEngine;using System.Collections;public class TestManager : Singleton<TestManager> {    void Awake () {        Debug.Log ("Awake");    }    // Use this for initialization    void Start () {        Debug.Log ("Start");    }    // Update is called once per frame    void Update () {    }    //我是测试的函数    public void show(){        Debug.Log ("你好啊,年轻人。");    }}

然后呢。。我们再写一个测试用脚本,随便挂在场景的一个物体上

using UnityEngine;using System.Collections;public class MyTest : MonoBehaviour {    // Use this for initialization    void Start () {        Debug.Log (TestManager.IsBuild);//是否创建实例? 答案肯定是否        TestManager.Instance.show ();//第1次测试        TestManager.Instance.show ();//第2次测试        TestManager.Instance.show ();//第3次测试        TestManager.Instance.show ();//第4次测试        TestManager.Instance.show ();//第5次测试,其实这几次也没啥大用。我就这么一写。        Debug.Log (TestManager.IsBuild);//是否创建实例?这次肯定是已经创建啦。    }    // Update is called once per frame    void Update () {    }}

运行一下:
这个是控制台输出
我们会发现单例模式并没有问题 (因为只Awake一次)。哈哈哈哈哈。让我感到快乐

但是最后的Start输出有点奇怪,其实是因为我是在MyTest 的Start()语句中调用的这一大堆函数,Unity本质上是单线程,所以。这个MyTest的Start()函数不结束。那么下一个TestManager 的Start函数就不会开始。就是这样。希望我能在后面讲解清楚Unity的函数执行顺序问题吧。(其实这段话没用。不看也行。单例没问题哦。)

以上参考自:(代码有所改动)

http://www.manew.com/forum.php?mod=viewthread&tid=16916

1 0