Thursday, January 21, 2016

c# - Why does Unity use reflection to get the update method?


Why does Unity use reflection in order to access MonoBehaviour message methods like Awake, Update, Start,...?


Wouldn't it be slow to use reflection? Why doesn't it leverage other approaches like Template Method? It could simply define the methods as abstract in MonoBehaviour base class and force the subclasses to implement it.



Answer





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.



As for the reasons it is done this way, I'll largely refer you (the reader) to DMGregory's answer, which boils down to a balance of two competing things:



  1. Performance optimization

  2. Ease of new developer utilization


A new developer just wants it to Work and doesn't want to have to figure out "how do I connect this in to the event system?" but it should still run fast with minimal overhead.


The solution is probably the best that can be achieved within these two constraints. Or at least, the best the Unity dev team was able to come up with at the time. We may never know.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...