Unity踩坑继承MonoBehaviour多次运行其构造函数

一、Unity继承MonoBehaviour多次运行构造函数

1.首先创建Test类继承MonoBehaviour

Unity踩坑继承MonoBehaviour多次运行其构造函数_第1张图片

在Unity中执行查看 可以看出从 挂载脚本——>运行——>结束一共执行了4次

Unity踩坑继承MonoBehaviour多次运行其构造函数_第2张图片

2.接下来我们在试试有参构造函数

Unity踩坑继承MonoBehaviour多次运行其构造函数_第3张图片

 Unity踩坑继承MonoBehaviour多次运行其构造函数_第4张图片

 有参函数缺不会多次执行

 官方说明:

Never initialize any values in the constructor. Instead use Awake or Start for this purpose. Unity automatically invokes the constructor even when in edit mode. This usually happens directly after compilation of a script, because the constructor needs to be invoked in order to retrieve default values of a script. Not only will the constructor be called at unforeseen times, it might also be called for prefabs or inactive game objects.
不要在构造函数中初始化任何变量.要用Awake或Start函数来实现.即便是在编辑模式,Unity仍会自动调用构造函数.这通常是在一个脚本编译之后,因为需要调用脚本的构造函数来取回脚本的默认值.我们无法预计何时调用构造函数,它或许会被预置体或未激活的游戏对象所调用.

原因官方文档也进行了说明,所以继承MonoBehaviour的类初始化变量需要在Awake或Start函数来实现。

总结:

继承MonoBehaviour的类会多次执行构造函数,虽然有参函数在测试时没有执行但还是根据官方文档所说初始化变量还是在Awake或Start函数来实现比较好

 

你可能感兴趣的:(c#)