【Unity】泛型单例类
程序员文章站
2022-04-03 15:36:42
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T instance;
public static T Instance
{
get { return instance; }
}
protected virtual void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = (T) this;
}
}
public static bool IsInitialized
{
get { return instance != null; }
}
protected virtual void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
}
使用时将需要设计为单例的类继承自该类即可
例如:
下一篇: Laravel 5文档阅读摘要