using UnityEngine; public abstract class Singleton : MonoBehaviour where T : Component { // 保存当前类型唯一的正式实例。 private static T instance; /// 取得当前类型的唯一实例。 public static T Instance { get { if (instance == null) { instance = FindObjectOfType(); if (instance == null) { GameObject obj = new GameObject(); obj.name = typeof(T).Name; instance = obj.AddComponent(); } } return instance; } } /// 保留第一个实例,并移除后来出现的重复对象。 protected virtual void Awake() { if (instance == null) { instance = this as T; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } }