using System.Collections; using System.Collections.Generic; using UnityEngine; public class PromptWinSingleton : MonoBehaviour where T : PromptWinSingleton { private static T instance = null; //静态锁 private static object _lock = new object(); public static T Instance { //获取对象 get { //加锁 lock (_lock) { if (instance == null) { instance = (T)FindObjectOfType(typeof(T)); if (FindObjectsOfType(typeof(T)).Length > 1) { Debug.LogError("[Singleton] 发生异常 " + " - 单例类只能有1个" + " 修复错误"); return instance; } if (instance == null) { GameObject singleton = new GameObject(); instance = singleton.AddComponent(); singleton.name = typeof(T).ToString() + "_singleton"; DontDestroyOnLoad(singleton); Debug.Log("[Singleton] " + typeof(T) + " 单例创建成功 " + instance.gameObject.name); } else { //Debug.Log("[Singleton] 已经创建: " + // instance.gameObject.name); } } //返回单例字段 return instance; } } } void OnApplicationQuit() { if (instance != null) instance = null; } }