How do the Unity private awake update and start methods work?

雨燕双飞 提交于 2019-12-10 10:46:37

问题


How does Unity call the Awake, Update, and Start methods behind the scene? That they have no access modifier to me indicates they are private methods, and they don't use anything like new or override, so how does the Unity framework find the methods to call them?

On a related question, is there any particular reason virtual methods were not used?

Edit: For those unfamiliar with Unity scripts, this is how they generally appear:

public class MyClass : MonoBehaviour{
   void Start(){
   }

   void Awake(){
   }

   void Update(){
   }
}

What I don't understand is how the framework finds and automatically calls those methods for each script when, by all appearances, they look to just be private methods


回答1:


Here is a piece of information in a Unity blog post

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.




回答2:


The reason the methods are not virtual is for performance. If it were virtual then every single MonoBehaviour would need all of the relevant methods called (Start, Awake, Update, FixedUpdate, etc.) which is a Bad Thing.



来源:https://stackoverflow.com/questions/42325033/how-do-the-unity-private-awake-update-and-start-methods-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!