Inheritance C# and OOP contructors (monobehavior) and Awake

Hello, I understand quite well that classes that inherited from Monobehavior should not use constructor.

But this is my case.

I have some 2 classes that are inherited from MonoBe.
This Classes have some commonc functionality that I would like to abstract to an upper (parent) class.

So I create some new Class “GeneralObject” that inherited from MonoB, and then make this 2 classes inherited from this one.

Ok, problem is that some of the properties a would like to abstract are common in the awake function.
This is, GenerlObject.Awake function should be called just like constructors in OO call (some times implicitly) its parent constructor.

But I have check that my GeneralObject Awake function is not called implicitly but must force its call from both sub-classes with “base.Awake()”.

So, this is the only way to invoke parent’s Awake from sub-classes or I’m missing something.

I understand that this is only one line of code but, wouldn’t be correct to parents Awake should be called implicitly just like constructors (due that in c# unity, Awake should be use as constructor).

Thanks.

That’s the only way to call overridden methods from overriding methods in C# (CLR). The code of the overridden method is not implicitly called as in the case of constructors.

For this type of problem, I believe it’s better to place these shared functions in a separate script and have your two separate classes access that script. This component based approach simply fits Unity better than the inheritance approach (as you have already found out with the constructor issue).

You could also have the parent Awake call a virtual Init method which the children then override. Or quite simply you could just require that the child classes should use Start and not Awake for initialization.

Thanks for your suggestions.

I quite understand both suggestions, if inheritance problems continue to come I will use component design instead of object large inheritance.

Anyway, in documentation says that Awake is called exactly once in script life time.
So… ¿is unity considering that the full descriptor of c# script (class) is only the most down in hierarchy?, because bases class are mono-behavior script and Awake is never called :wink:

I think that is some kind of bug, or it is a “design decision” even when doest not accomplish sometimes the affirmation in the docs?

Thank you.

The reason that Awake works as it does, is because it is not implemented as a virtual function. Basically, Unity uses reflection to find the Awake (and Update, Start, etc…) function and calls that. In practice, this means the Awake function of the base class is “overridden” by the Awake of the child class. This is only the case for these special monobehaviour functions, you can add your own virtual functions to your classes and they will work as expected.