1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System;
- using UnityEngine;
- public class MonoSingletonDontDestory<T> : 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<T>();
- 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<T>();
- DontDestroyOnLoad(go);
- }
- else
- {
- _insatnce = instances[0];
- }
- }
- return _insatnce;
- }
- }
- }
- protected virtual void OnApplicationQuit()
- {
- _insatnce = null;
- }
- protected virtual void OnDestory()
- {
- _insatnce = null;
- }
- }
|