using System;
using System.Collections;
using System.Collections.Generic;
namespace Victor_Wang.Utilities //可以换成你自己的命名空间
{
public class Singleton<T> where T : class
{
private static volatile T _instance;//volatile可以确保_instance的读取每次都是从内存中读取而不是缓存中
private static object lack = new object();
protected Singleton(){ }
public static T Instance
{
get
{
if (_instance == null)//先判空节省性能
{
lock (lack)
{
if (_instance == null)//确保当前线程等待锁的时候其他线程创建了实例
{
_instance = Activator.CreateInstance(typeof(T), true) as T;
}
}
}
return _instance;
}
}
public void Destroy()
{
_instance = null;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Victor_Wang.Utilities
{
/// <summary>
/// Mono单例
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
protected static T instance;
private static readonly object locker = new object();
private static bool _applicationIsQuitting = false;//在应用程序退出时防止创建新的单例实例
public static T Instance
{
get
{
if (_applicationIsQuitting)
{
return null;
}
lock (locker)
{
if (instance == null)
{
instance = FindObjectOfType<T>();//遍历场景中所有的游戏对象,返回场景中T类型的第一个实例
if (instance == null)
{
GameObject singleton = new GameObject();
singleton.AddComponent<T>();
singleton.name = "Singleton" + typeof(T).ToString();
DontDestroyOnLoad(singleton);
}
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
protected virtual void OnDestroy()
{
if (instance == this)
{
_applicationIsQuitting = true;
}
}
}
}