通常用法是在相关类加入GetInstance()的静态方法,检查实例是否存在。如果存在,则返回。如果不存在,则返回一个“需要用游戏元素类关联”的调试警告错误。
public class MyClass
{
private static MyClass instance;
public static MyClass GetInstance()
{
if (!instance)
{
instance = GameObject.FindObjectOfType(typeof(MyClass));
if (!instance)
Debug.LogError("There needs to be one active MyClass script on a GameObject in your scene.");
}
return instance;
}
}