单例模式的实现Singleton和MonoSingleton
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 普通单例基类
/// by:zdz
/// date:20220328
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T : new()
{
private static T m_instance;
private static readonly object locker = new object();
public static T Instance
{
get
{
lock (locker)
{
if (m_instance == null) m_instance = new T();
}
return m_instance;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Mono单例基类
/// by:zdz
/// date:20220328
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T> : MonoBehaviour where T:Component
{
private static T m_instace;
private static readonly object lockObj=new object();
public static T Instance
{
get
{
lock (lockObj)
{
m_instace = FindObjectOfType<T>();
if (m_instace == null)
{
GameObject obj = new GameObject("TempObj");
m_instace = obj.AddComponent<T>();
}
}
return m_instace;
}
}
}