`
java-mans
  • 浏览: 11436337 次
文章分类
社区版块
存档分类
最新评论

MonoBehaviour的单例模式

 
阅读更多

我们有一个继承自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;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics