using UnityEngine;
public class SingleMono<T> : MonoBehaviour where T : MonoBehaviour
{
static protected T _instance;
static public T instance
{
get
{
Create();
return _instance;
}
}
static protected void Create()
{
if (_instance == null)
{
GameObject temp = new GameObject(typeof(T).Name);
_instance = temp.AddComponent<T>();
}
}
protected virtual void Awake()
{
T t = this.GetComponent<T>();
if (_instance == null)
{
_instance = t;
}
else
{
if (_instance != t)
{
this.GetComponent<T>();
Debug.LogErrorFormat("The [{0}] already exists", this.GetType().Name);
Destroy(this.gameObject);
}
}
}
}

博客给出了在Unity游戏引擎中实现单例模式的代码。定义了一个泛型类SingleMono,包含静态实例属性和创建实例的方法,在Awake方法中处理实例的初始化和重复实例的销毁,确保单例的唯一性。
4776

被折叠的 条评论
为什么被折叠?



