Unity3D单例模板

using UnityEngine;
public class Singleton : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    private static object _lock = new object();
    public static T Instance
    {
        get
        {
            if (applicationIsQuitting) {
                return null;
            }
            lock(_lock)
            {
                if (_instance == null)
                {
                    _instance = (T) FindObjectOfType(typeof(T));
                    
                    if ( FindObjectsOfType(typeof(T)).Length > 1 )
                    {
                        return _instance;
                    }
                    
                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent();
                        singleton.name = "(singleton)_"+ typeof(T).ToString();
                        
                        DontDestroyOnLoad(singleton);
                    }
                }
                
                return _instance;
            }
        }
    }
    
    private static bool applicationIsQuitting = false;

    public void OnDestroy () {
        applicationIsQuitting = true;
    }
}

       这个类实现了多线程锁机制,能够保护数据安全,如果场景中没有该类的话,会自动创建一个名为“(singleton)_ + 类名”的物体,DontDestroyOnLoad确保该物体在切换场景的时也不会销毁,所以游戏运行中有且仅有一个该类。

你可能感兴趣的:(游戏开发,Unity)