using System; using UnityEngine; public class MonoSingletonDontDestory : MonoBehaviour where T : MonoBehaviour { protected static T _insatnce; protected static object _lock = new object(); public static T Instance { get { lock (_lock) { if (_insatnce == null) { var instances = FindObjectsOfType(); if (instances.Length > 1) { throw new Exception(string.Format("场景中存在多个类型为:{0}的脚本", typeof(T).ToString())); } else if (instances.Length == 0) { var go = new GameObject(typeof(T).ToString() + "(MonoSingleton)"); _insatnce = go.AddComponent(); DontDestroyOnLoad(go); } else { _insatnce = instances[0]; } } return _insatnce; } } } protected virtual void OnApplicationQuit() { _insatnce = null; } protected virtual void OnDestory() { _insatnce = null; } }