- Home /
Why does MonoBehaviour not allow message functions to be overridden?
I constantly forget what the message functions names are when working with Unity, i.e Awake, Start, OnEnable etc. So for 20 minutes the other day I had an OnEnabled function and was wondering why it was not being invoked, whereas it should have been OnEnable, however there is no interface or virtual method indicating that you should override it if you want to be able to hook into these events.
So I was just wondering is there a particular reason why these methods are not virtual or at least already defined in some way for you to know what they are and override them?
I will assume they are not virtual because of the overhead of virtual methods, and they cannot be abstract because then you are forced to implement them, and finally are not on an interface and empty because then you would need to do some funky new function over the top of the other.
It just seems that there should be a better way to do this without me needing a cheat sheet to see what methods unity will allow me to hook into, especially as c# provides such good intellisense these days.
Answer by kacyesp · Sep 01, 2014 at 08:45 AM
What do you mean "there is no interface" ? Does the documentation for Monobehaviour not count? http://docs.unity3d.com/ScriptReference/MonoBehaviour.html
You're right about not using virtual methods to reduce needless overhead, and that's why Unity uses reflection, which is just a fancy way of saying that Unity only calls on the methods if they are implemented. If they aren't implemented, then they aren't called at all.
Well yes there is documentation, however when you open up in your IDE and start off with your monobehaviour class, you either have to recall from memory what the message names are or load up the documentation, and there is no compile time safety around this. This is my worry, as listed above a typo wont be caught so your code wont work and you are open to human error.
The interface comment was around if they had an I$$anonymous$$onoBehaviour$$anonymous$$essages then at least you could not have virtuals and just overwrite the method functions defined on the interface, but at least you would SEE the available functions then. Also reflection is DREADFULLY slow, if not slower than virtual calls, although I presume they do it in some way making it more efficient.
Anyway my ultimate concern is that I HAVE to currently have a list of the available unity methods available to enter and I have no compile time/intellisense safety around this.
@$$anonymous$$acro Oh I see what you're saying now. Well if you're really concerned about this, for now you could always implement your own interface and let the guys at Unity know you want compile time safety: http://feedback.unity3d.com/ I agree that overriding the message functions would be nice.