我们有一个继承自MonoBehaviour的类是用来做对象交互动作的,想做成单例的,写成通用的方法报错。
private static Communication instance;
public static Communication GetInstance()
{
if(instance==null){
instance=new Communication();
}
return instance;
}
提示:You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
网上找到了解决方案,系统会自动创建MonoBehaviour 对象,在其awake时候设置其instane即可。
正确代码如下:
private static Communication instance;
public static Communication GetInstance()
{
return instance;
}
void Awake() {
instance = this;
}