using System; using System.Reflection; using UnityEngine; public abstract class BaseManager where T : class { // 使用 volatile 关键字确保在多线程环境下 instance 字段的可见性和有序性 // 防止双重检查锁定模式中的内存重排序问题 private static volatile T instance; protected static readonly object lockObj = new object(); public static T Instance { get { // 第一次检查:如果 instance 不为 null,直接返回,避免不必要的锁操作 if (instance == null) { lock (lockObj) { // 第二次检查:在锁内再次检查,确保只有一个线程创建实例 if (instance == null) { instance = (T)Activator.CreateInstance(typeof(T), true); } } } return instance; } } public virtual void Destroy() { instance = null; } }