Unity 单例模式实现代码及使用方法
以下是 Unity 的单例模式实现代码:
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
使用方法:
- 创建一个继承自 Singleton 的类,例如:
public class GameManager : Singleton<GameManager>
{
// 在这里添加 GameManager 类的成员变量和成员方法
}
- 在其他脚本中调用单例:
GameManager.Instance.DoSomething();
原文地址: https://www.cveoy.top/t/topic/lM1c 著作权归作者所有。请勿转载和采集!