Unity 5项目在Unity 2020.2.7f1打开出现new关键字不允许警告如何解决
问题原因
你的FuzzySet类继承了MonoBehaviour类,Unity引擎明确规定所有继承自MonoBehaviour的类不允许使用new关键字手动调用构造函数实例化,Unity 5对该规则校验宽松不会弹出警告,升级到2020版本后严格触发了规则校验。
修复方案
你可以根据自己的使用需求二选一:
- 方案1:如果
FuzzySet无需作为组件挂载到游戏对象上,仅作为普通数据类使用,直接删除FuzzySet类定义末尾的: MonoBehaviour继承声明即可,保留现有new实例化的代码不会再触发警告。 - 方案2:如果
FuzzySet确实需要继承MonoBehaviour,需要修改实例化逻辑:- 删除
FuzzySet类中自定义的构造函数,MonoBehaviour不允许存在自定义构造函数,相关初始化逻辑可以挪到Awake/Start生命周期方法,或者单独写公共初始化方法 - 将
Speed_Control.cs中的静态变量实例化逻辑修改为通过AddComponent实现,示例代码如下:
public static FuzzySet Foresight; public static FuzzySet RoadWidth; public static FuzzySet CarInFront; public static FuzzySet Distance; public static FuzzySet Speed; private void Awake() { Foresight = CreateFuzzySetInstance("Foresight"); RoadWidth = CreateFuzzySetInstance("Road Width"); CarInFront = CreateFuzzySetInstance("Cars in front"); Distance = CreateFuzzySetInstance("Distance to the intersection"); Speed = CreateFuzzySetInstance("Safe Speed"); } private FuzzySet CreateFuzzySetInstance(string name) { GameObject obj = new GameObject(name); FuzzySet fs = obj.AddComponent<FuzzySet>(); // 这里补充给FuzzySet其他属性赋值的逻辑 return fs; } - 删除
相关参考信息
FuzzySet.cs代码
public string[] tenBNN = new string[10]; //so bien ngon ngu public int SoBNN = 0; public FuzzySet(string a) { _name = a; }
Speed_Control.cs代码
public static FuzzySet Foresight = new FuzzySet("Foresight"); public static FuzzySet RoadWidth = new FuzzySet("Road Width"); public static FuzzySet CarInFront = new FuzzySet("Cars in front"); public static FuzzySet Distance = new FuzzySet("Distance to the intersection"); public static FuzzySet Speed = new FuzzySet("Safe Speed");
警告截图

内容的提问来源于stack exchange,提问作者vidha rossa pratiwi
相关产品推荐
相关产品推荐

