Test-TaizhouWarehousePhaseII/3d/Assets/Zion/Scripts/Utility/BaseManager.cs

38 lines
1.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Reflection;
using UnityEngine;
public abstract class BaseManager<T> 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;
}
}