赞
踩
public class SceneMgr { private static SceneMgr _Instance; /// <summary> /// 只读 /// </summary> public static SceneMgr Instance { get { if(_Instance==null) { _Instance = new SceneMgr(); } return _Instance; } } public void TestLog() { Debug.Log("执行单例"); } }
/// <summary> /// 单例 /// </summary> /// <typeparam name="T">子类继承时候会传给单例一个类型,且要求实例化</typeparam> public class Singleton<T>:IDisposable where T:new() { private static T instance; public static T Instance { get { if(instance==null) { instance = new T(); } return instance; } } } public class SceneMgr : Singleton<SceneMgr> { }
Unity中继承MonoBehaviour脚本有两个特性:
public class BoxCtrl : MonoBehaviour { private static BoxCtrl _Instance; public static BoxCtrl Instance { get { if(_Instance==null) { //创建一个新的物体 GameObject obj = new GameObject("BoxCtrl"); //将单例挂载在物体上 _Instance = obj.AddComponent<BoxCtrl>(); //使得加载场景时候,物体不会被摧毁 DontDestroyOnLoad(obj); } return _Instance; } } public void Test() { Debug.Log("执行BoxCtrl单例"); } }
还有一种简单的单例方法,这种单例方法很简单,但是在当前场景中只能存在一个该脚本。
public class BoxCtrl : MonoBehaviour
{
public static BoxCtrl Instance;
void Awake()
{
Instance = this;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。