Why are the MonoBehaviour methods not implemented for overriding?

前端 未结 1 514
刺人心
刺人心 2021-01-12 06:25

In Unity3d you have the MonoBehaviour class, which is the normal base class for all scripts. When implementing a script, one has to implement the m

1条回答
  •  再見小時候
    2021-01-12 06:49

    If you check the documentation you will see that all those 'functions' are listed in the 'Messages' section; MonoBehaviour Doc.

    So that means that 'functions' (like Start, OnEnable or Awake), they are not implemented as methods but as messages.

    Now, MonoBehaviour inherits from Behaviour, which inherits from Component which has the SendMessage method. That method basically calls a message/method with the option to report an error if the message/method exists or not. The parameter of the name message/method is a string, /~~so they are using reflection there.~~/ Check Update!!

    Seems like Unity behind the scenes determines if those messages were implemented to see if it has to call them or not. According to this UnityAnswer:

    Unity is mainly written in c++ and therefore most magic happens in native code. Unity uses reflection to determine, after your scripts have been compiled, what of those "events" you've implemented and remember that for this class. Unity only calls Update / LateUpdate / OnGUI when it has been implemented.

    So, the short answer is, they are not 'real' methods that you have to override, they are messages that are called only if they were implemented.


    Update; As @Raining noted, I was wrong in the way that Unity obtains the messages to call. Unity doesn't use reflection to do this. According this 1k-update-calls (also provided by @Rainin) scripts are inspected to check if they contain some of those 'magic methods'. If so, they are added to lists that will be executed accordingly.

    0 讨论(0)
提交回复
热议问题