using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T : new()
{
private static T _instance;
private static object mutex = new object();
public static T instance
{
get
{
if (_instance == null)
{
lock (mutex)//线程安全
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
}
//Unity 单例
public class MonoSingleton<T> : MonoBehaviour where T : Component
{
private static T _instance = null;
public static T Instance
{
get
{
if(_instance == null)
{
_instance = FindObjectOfType(typeof(T)) as T;
if(_instance == null)
{
GameObject obj = new GameObject(typeof(T).Name + " (instance)");
_instance = (T)obj.AddComponent(typeof(T));
obj.hideFlags = HideFlags.DontSave;
}
}
return _instance;
}
}
protected virtual void Awake()
{
if(_instance == null)
{
_instance = this as T;
}
else
{
GameObject.Destroy(this.gameObject);
}
}
}
单例 Singleton
最新推荐文章于 2024-06-05 20:13:10 发布