1

I'm working on a Unity project which uses a good amount of inheritance. I have an abstract base class whose methods I want its children to always call (e.g. Awake).

I haven't worked with attributes much - is there a way to add an attribute to my ABC's Awake method which causes the child-class to log an error if they override Awake() without calling base.Awake() in its implementation?

Thanks!

  • Rather than demanding the child class call your base implementation of Awake, why not create an abstract protected DoAwake() method in your base class and then avoid making your Awake method virtual? – Adam G Apr 13 '21 at 04:25

1 Answers1

1

You could something like this:

public class A 
{
    public void Awake() 
    {
        Console.WriteLine("Everybody does X on awake");
        AwakeExtra();
    }

    public virtual void AwakeExtra() => Console.WriteLine("'A' also does A on awake");
}

public class B : A 
{
    public override void AwakeExtra() => Console.WriteLine("'B' also does B on awake");
}
tymtam
  • 31,798
  • 8
  • 86
  • 126