Why Update or Start functions in C# class scripts that are chidren of MonoBehaviour ( of course) can't be overrided (keyword override C#), when the functions are declared as overridable? Is it automatically overided like in C++ when you declare/implement a function that is overridable?
hi there is a really good book about C# for programmers "programming C# 3" by jessie liberty publisher: oreilly this is implicitly done in unity. i am not sure but i
Unity doesn't use virtual functions to implement the callback system for MonoBehaviours. It uses reflection to see which functions are implemented and will only perform callbacks on those functions it can find. This is also why your Start function gets called even if it is defined as private.
if you still do want to have such behaviour (which I would expect too btw) in your scripts you could achieve this prety easily with a little level of indirection in your scripts. something along those lines : Code (csharp): public class VirtualBehaviour : MonoBehaviour { void Update(){ doUpdate(); } protected virtual void DoUpdate(){} void Wake(){ DoWake(); } protected virtual void DoWake(){} void Start(){ DoStart(); } protected virtual void DoStart(){} }
The reason Unity uses reflection over virtual functions, is that with the latter it has to call Update, LateUpdate, FixedUpdate and all the other callback on every single MonoBehaviour every frame (or at whatever frequency the function is supposed to be called). For large projects with large numbers of objects, that may result in significant performance overhead as most MonoBehaviours don't need every possible callback. In fact, in most scripts I write don't implement more than 3 or 4 of the close to 50 possible MonoBehaviour callbacks. I wouldn't recommend working against Unity by forcing everything to be virtual. There is no advantage to doing that, only drawbacks.