废话不多说,记录自己常用的单例模式代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
public class GlobalSingleton<T> : MonoBehaviour, IInstance where T : MonoBehaviour, IInstance
{
private static readonly object _lock = new object();
private static bool IsQuit = false;
private static bool IsInit = false;
private static T _instance;
public static T Instance
{
get
{
if (IsQuit) return null;
lock (_lock)
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(GSingleton) " + typeof(T).ToString();
singleton.transform.position = Vector3.zero;
singleton.transform.rotation = Quaternion.identity;
singleton.transform.localScale = Vector3.one;
}
DontDestroyOnLoad(_instance.gameObject);
}
if (!IsInit)
{
_instance.Init();
IsInit = true;
}
return _instance;
}
}
}
public virtual void Init() { }
private void OnDestroy()
{
IsQuit = true;
}
}
public interface IInstance
{
void Init();
}