模版类
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
/**
Returns the instance of this singleton.
*/
public static T Instance
{
get
{
if(instance == null)
{
instance = (T) FindObjectOfType(typeof(T));
if (instance == null)
{
Debug.LogError("An instance of " + typeof(T) +
" is needed in the scene, but there is none.");
}
}
return instance;
}
}
}
下面是子类
public class ChildrenClass : Singleton<ChildrenClass>{
void Update{
}
}
这样 ChildrenClass 就是一个单例,并且继承了 MonoBehaviour 的功能。