轉載自:https://blog.csdn.net/smilelance/article/details/7839878
我們有一個繼承自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;
}