using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T: MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
_instance = (T)FindObjectOfType(typeof(T));
if(FindObjectsOfType(typeof(T)).Length>1)
{
Debug.LogError("存在多个" + typeof(T).Name);
return _instance;
}
}
}
return _instance;
}
}
}
public class Singleton<T> where T : class, new()
{
private static readonly object syslock = new object();
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
lock (syslock)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
}
两种单例工具
于 2021-10-14 23:23:48 首次发布