Unity中的单例模式基类

发表于2018-05-08
评论0 2.5k浏览
在unity中有两种单例类型,一种是普通单例,即普通c#类,另一种是继承了MonoBehaviour的单例。

普通单例:
public abstract class CSharpSingletion<T> where T : new() {  
    private static T instance;  
    public static T Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                instance = new T();  
            }  
            return instance;  
        }  
    }  
} 

继承了MonoBehaviour的单例:
using UnityEngine;  
using System.Collections;  
public abstract class MonoSingletion<T> : MonoBehaviour where T : MonoBehaviour {  
    private static string rootName = "MonoSingletionRoot";  
    private static GameObject monoSingletionRoot;  
    private static T instance;  
    public static T Instance  
    {  
        get  
        {  
            if (monoSingletionRoot == null)  
            {  
                monoSingletionRoot = GameObject.Find(rootName);  
                if (monoSingletionRoot == null) Debug.Log("please create a gameobject named " + rootName);  
            }  
            if (instance == null)  
            {  
                instance = monoSingletionRoot.GetComponent<T>();  
                if (instance == null) instance = monoSingletionRoot.AddComponent<T>();  
            }  
            return instance;  
        }  
    }  
}  

第二种需要在场景中创建一个名为MonoSingletionRoot的空物体,才能使用。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引