本文主要是介绍Unity3D设计模式之单例模式(1),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
单例模式有三大要点:
一、是每个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。
下面是几种写法:一、
public class Singleton
{
static Singleton instance;
public static Singleton Instance {
get {
if (instance == null) {
instance = new Singleton ();
}
return instance;
}
}
}
二、
public class Sigleton : MonoBehaviour
{
private static Sigleton instance;
public static Sigleton Instance
{
get{
if (instance == null)
{
instance = this ;
}
return instance;
}
}
void Awake()
{
instance = this;
}
}
三、
public class Singleton<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = new T ();
}
return instance;
}
}
}
四、
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance{
get { return Singleton<T>.instance; }
}
void Awake()
{
if (instance == null)
{
instance = GetComponent<T>();
}
}
void OnApplicationQuit()
{
instance = null;
Debug.Log("quit");
}
}
五、
public class Singletion<T> : MonoBehaviour where T : MonoBehaviour
{
private static string rootName = "SingletionRoot";
private static GameObject SingletionRoot;
private static T instance;
public static T Instance
{
get
{
if (monoSingletionRoot == null)
{
SingletionRoot = GameObject.Find(rootName);
if (SingletionRoot == null) Debug.Log("please create a gameobject named " + rootName);
}
if (instance == null)
{
instance = SingletionRoot.GetComponent<T>();
if (instance == null) instance = SingletionRoot.AddComponent<T>();
}
return instance;
}
}
}
六、
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{
private static T instance;
public static T Instance {
get {
if ( instance == null ) {
GameObject obj = new GameObject("Singleton");
// 隐藏实例化的new game object,下同
//obj.hideFlags = HideFlags.HideAndDontSave;
// 不删除该物体
DontDestroyOnLoad(obj);
instance = obj.AddComponent(typeof(T)) as T;
}
return _instance;
}
}
}
七、
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{
private static object lock = new object();
protected static T instance;
public static T instance{
get{
lock(lock)
{
if(instance == null)
{
instance = FindObjectOfType<T>();
if(instance == null)
{
GameObject singleton = new GameObject();
singleton.name = "Singleton_" + typeof(T).ToString();
singleton.hideFlags = HideFlags.HideAndDontSave;
instance = singleton.AddComponent<T>();
}
}
return instance;
}
}
}
这篇关于Unity3D设计模式之单例模式(1)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!