Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Unity execute its methods?

Tags:

c#

unity3d

I only have a small experience in Unity3D, but I noticed that classes that derive from MonoBehaviour may contain functions with predefined signatures that will be called in a special way. For instance, if I write:

void Update()
{
  //some code
}

this method will be called every frame.

I imagine that inside Unity there is some sort of an endless loop that calls the Update method every frame for each object on the scene. But how does it know that the object actually provides the Update method implementation? It would have been 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) it's not. Is there some reflection magic happening there?

like image 261
bashis Avatar asked Jan 26 '16 09:01

bashis


1 Answers

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

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.

like image 189
Jerry Switalski Avatar answered Oct 09 '22 16:10

Jerry Switalski