Unity 私有唤醒更新和启动方法如何工作?
How do the Unity private awake update and start methods work?
Unity是如何在后台调用Awake、Update、Start方法的?它们对我来说没有访问修饰符表明它们是私有方法,并且它们不使用任何类似 new 或 override 的东西,那么 Unity 框架如何找到调用它们的方法?
关于相关问题,没有使用虚方法有什么特殊原因吗?
编辑:对于那些不熟悉 Unity 脚本的人,它们通常是这样显示的:
public class MyClass : MonoBehaviour{
void Start(){
}
void Awake(){
}
void Update(){
}
}
我不明白的是框架是如何为每个脚本找到并自动调用这些方法的,而从表面上看,它们看起来只是私有方法
中的一条信息
HOW UPDATE IS CALLED
No, Unity doesn’t use System.Reflection to find a magic method every time it needs to call one.
Instead, the first time a MonoBehaviour of a given type is accessed the underlying script is inspected through scripting runtime (either Mono or IL2CPP) whether it has any magic methods defined and this information is cached. If a MonoBehaviour has a specific method it is added to a proper list, for example if a script has Update method defined it is added to a list of scripts which need to be updated every frame.
During the game Unity just iterates through these lists and executes methods from it — that simple. Also, this is why it doesn’t matter if your Update method is public or private.
方法不是虚拟的是为了性能。如果它是虚拟的,那么每个 MonoBehaviour 都需要调用所有相关方法(Start、Awake、Update、FixedUpdate 等),这是一件坏事。
Unity是如何在后台调用Awake、Update、Start方法的?它们对我来说没有访问修饰符表明它们是私有方法,并且它们不使用任何类似 new 或 override 的东西,那么 Unity 框架如何找到调用它们的方法?
关于相关问题,没有使用虚方法有什么特殊原因吗?
编辑:对于那些不熟悉 Unity 脚本的人,它们通常是这样显示的:
public class MyClass : MonoBehaviour{
void Start(){
}
void Awake(){
}
void Update(){
}
}
我不明白的是框架是如何为每个脚本找到并自动调用这些方法的,而从表面上看,它们看起来只是私有方法
HOW UPDATE IS CALLED
No, Unity doesn’t use System.Reflection to find a magic method every time it needs to call one.
Instead, the first time a MonoBehaviour of a given type is accessed the underlying script is inspected through scripting runtime (either Mono or IL2CPP) whether it has any magic methods defined and this information is cached. If a MonoBehaviour has a specific method it is added to a proper list, for example if a script has Update method defined it is added to a list of scripts which need to be updated every frame.
During the game Unity just iterates through these lists and executes methods from it — that simple. Also, this is why it doesn’t matter if your Update method is public or private.
方法不是虚拟的是为了性能。如果它是虚拟的,那么每个 MonoBehaviour 都需要调用所有相关方法(Start、Awake、Update、FixedUpdate 等),这是一件坏事。