unity3d 常用模式——单例模式

来源:互联网 发布:java中配置文件是什么 编辑:程序博客网 时间:2024/06/07 19:11

用unity3d,经常用到单例,一直觉得单例很简单,但是不断发现有各种问题,经常修改维护;偶尔间发现自己的单例写的有多水了。

http://unitypatterns.com/singletons/;里面讲到了3种,之前用的是里面讲到的第一种方式

第三种是一种相当完美的单例实现了,如下:

public class MusicManager : MonoBehaviour {    private static MusicManager _instance;    public static MusicManager instance    {        get        {            if(_instance == null)            {                _instance = GameObject.FindObjectOfType<MusicManager>();                //Tell unity not to destroy this object when loading a new scene!                DontDestroyOnLoad(_instance.gameObject);            }            return _instance;        }    }    void Awake()     {        if(_instance == null)        {            //If I am the first instance, make me the Singleton            _instance = this;            DontDestroyOnLoad(this);        }        else        {            //If a Singleton already exists and you find            //another reference in scene, destroy it!            if(this != _instance)                Destroy(this.gameObject);        }    }    public void Play()    {        //Play some audio!    }}

以后就用这种实现了,起码看上去比第一种高大上了大笑

0 0