Can I/Should I call Awake() in parent class manually?

I’m having an issue where Awake() in a child class is hiding Awake() in the parent.

I have this:

public class BaseClass: MonoBehaviour {
  void Awake () {
    Debug.Log("BaseClass Awake!");
    //do base class set up stuff
  }
}

…and then the child class:

public class ChildClass: BaseClass {
  void Awake(){
    //do child class setup stuff
  }
}

…but of course Awake() in ChildClass is “occluding” Awake() in BaseClass, so I don’t see the Debug.Log, etc. My understanding is that this is the correct C# behavior.

What I want to do is something like:

public class ChildClass: BaseClass {
  void Awake(){
    //make sure base setup is done
    base.Awake();

    //do child class setup stuff
  }
}

…but I’ve hit my limit of C# understanding! Is there a right way to do this? Or should I be looking at the whole situation differently?

You should use public virtual on you baseclass method and use public override in your inheriting class if you want to override it but be able to access the parent’s Awake() too.

baseclass

public virtual void Awake() { // baseclass stuff }

child

public override void Awake() { base.Awake(); // and child stuff }

This will call the baseclass’s method, then the child’s method body. You have to make them public because virtual or abstract members cannot be private, you get a compiler error if you omit the public accessor on any of them.

Another thing you could do is define a virtual void OnAwake() in you baseclass, which is empty, and code your baseclass’ Awake in Awake(), then call OnAwake() (or really any method) from the base Awake, like this:

/// in baseclass:
public virtual void OnAwake();
void Awake() {
   // do baseclass awake stuff
   OnAwake();
}

/// in inheriting class:
public override void OnAwake() {
   // do subclass stuff
}

Although base.Awake() has more control since you can specify if it runs before or after (or somewhere between) your inherited class’s routine, depending on when do you call it (but for sake of clarity you should write your code so base.anything is the first thing you do in a method). Also if you have multiple levels of inheriting classes, this can become erroneous, so use the base.Awake() approach, because it will execute every parent class’s code.