50 lines
1.2 KiB
C#
50 lines
1.2 KiB
C#
using UnityEngine;
|
|
|
|
// 单例模板
|
|
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
// 静态变量用于保存唯一实例
|
|
private static T _instance;
|
|
|
|
// 公共属性,用于外部访问实例
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
// 如果实例为空,尝试查找场景中的实例
|
|
if (_instance == null)
|
|
{
|
|
_instance = FindObjectOfType<T>();
|
|
|
|
// 如果场景中没有实例,创建一个新的实例
|
|
if (_instance == null)
|
|
{
|
|
GameObject singletonObject = new GameObject(typeof(T).Name);
|
|
_instance = singletonObject.AddComponent<T>();
|
|
}
|
|
}
|
|
|
|
// 返回实例
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
// 在需要时添加你的其他变量和方法
|
|
|
|
protected virtual void Awake()
|
|
{
|
|
// 确保只有一个实例存在,如果已经有实例存在则销毁新的实例
|
|
if (_instance != null && _instance != this)
|
|
{
|
|
Destroy(this.gameObject);
|
|
}
|
|
else
|
|
{
|
|
_instance = this as T;
|
|
//DontDestroyOnLoad(this.gameObject); // 防止切换场景时销毁实例
|
|
}
|
|
}
|
|
|
|
// 在需要时添加其他方法和逻辑
|
|
}
|