1 using UnityEngine; 2 using System.Collections; 3 4 public class SingleMono<T> : MonoBehaviour where T : MonoBehaviour 5 { 6 private static T _instance; 7 public static T Instance() 8 { 9 if (_instance == null) 10 { 11 _instance = (T)FindObjectOfType(typeof(T)); 12 if (_instance == null) 13 { 14 GameObject singleton = new GameObject(); 15 _instance = singleton.AddComponent<T>(); 16 singleton.name = "(singleton) " + typeof(T).ToString(); 17 DontDestroyOnLoad(singleton); 18 } 19 } 20 return _instance; 21 } 22 }
Tips:FindObjectOfType<Type type> 返回类型为type的活动的第一个对象