如何设计?
先分析下需求:
1.约束脚本实例对象的个数。
2.约束GameObject的个数。
3.接收MonoBehaviour生命周期。
4.销毁单例和对应的GameObject。
首先,第一点,约束脚本实例对象的个数,这个在上一篇中已经实现了。
但是第二点,约束GameObject的个数,这个需求,还没有思路,只好在游戏运行时判断有多少个GameObject已经挂上了该脚本,然后如果个数大于1抛出错误即可。
第三点,通过继承MonoBehaviour实现,只要覆写相应的回调方法即可。 第四点,在脚本销毁时,把静态实例置空。 完整的代码就如下所示:
using UnityEngine;
namespace QFramework
{
public abstract class QMonoSingleton<T>:MonoBehaviour where T :QMonoSingleton <T>
{
protected static T instance = null;
public static T InStance()
{
if(instance ==null )
{
instance = FindObjectOfType<T>();
if(FindObjectsOfType <T>().Length >1)
{
return instance;
}
if(instance ==null )
{
string instanceName = typeof(T).Name;
GameObject instanceGO = GameObject.Find(instanceName);
if(instanceGO ==null )
{
instanceGO = new GameObject(instanceName);
}
instance = instanceGO.AddComponent<T>();
DontDestroyOnLoad(instanceGO);
}
else
{
//已经存在实例了
}
}
return instance;
}
protected virtual void OnDestroy()
{
instance = null;
}
}
}