我们有一个继承自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;
}
本文详细介绍了如何将继承自MonoBehaviour的类转化为单例模式,并在Awake方法中进行实例设置,避免使用new关键字直接创建MonoBehaviour对象。通过实例化过程的调整,确保游戏对象的生命周期管理更加高效。
4762

被折叠的 条评论
为什么被折叠?



