UnityC#单例模式父类实现

New方式实现单例

/// 
/// 单例创建器
/// 
public class Single where T : class, new()
{
    private static T _instance;
    private static readonly object syslock = new object();
    public static T instance
    {
        get
        {
            if (_instance == null)
            {
                lock (syslock)
                {
                    _instance = new T();
                }
            }
            return _instance;
        }
    }
}

MonoBehaviour实现单例

/// 
/// 单例创建器
/// 
public class SingleMonoBehaviour : MonoBehaviour where T : MonoBehaviour
{
    private static GameObject gObj = null;
    private static T _instance;
    private static readonly object syslock = new object();
    public static T instance
    {
        get
        {
            if (_instance == null)
            {
                lock (syslock)
                {
                    _instance = GameObject.FindObjectOfType();
                    if (_instance == null)
                    {
                        if (gObj == null) gObj = new GameObject("SingleMonoBehaviour");
                        _instance = gObj.AddComponent();
                        GameObject.DontDestroyOnLoad(gObj);
                    }
                    else
                    {
                        GameObject.DontDestroyOnLoad(_instance.gameObject);
                    }
                }
            }
            return _instance;
        }
    }
}

 

你可能感兴趣的:(Unity,unity3d,c#)