How does Unity execute its methods?

I only have a little experience with Unity3D, but I noticed that classes that come from MonoBehaviour can contain functions with predefined signatures that will be called in a special way. For example, if I write:

 void Update() { //some code } 

this method will be called every frame.

I assume that inside Unity there is some kind of infinite loop that calls the Update method for every frame for every object on the scene. But how does he know that the object actually implements the implementation of the Update method? It would be clear if Update was an override for a method in the MonoBehaviour class, but judging by the syntax (and the fact that you can implement such methods with any access modifier), this is not the case. Is there some kind of reflection magic?

+5
source share
1 answer

http://blogs.unity3d.com/2015/12/23/1k-update-calls/

No, Unity does not use System.Reflection to find the magic method every time it takes to call.

Instead, the first time you access MonoBehaviour of a certain type, the base script is checked through the execution time of the scripts (either Mono or IL2CPP), if it has any magic methods, certain information is cached. If MonoBehaviour has a specific method, this is added to the correct list, for example, if the script has an update method, it is added to the list of scripts that need to be updated every frame.

During the game, Unity simply iterates over these lists and executes methods from it - it's simple. Also, therefore, it doesn’t matter if your update method is public or private.

+7
source

Source: https://habr.com/ru/post/1241475/


All Articles