Zedd
Zedd

Reputation: 167

(Unity) How to prevent MonoBehavior Awake() function overriding in children

Is it possible to disable the option to override MonoBehavior functions like Start(), Awake(), Update(), etc... in children class?

The reason behind this is, that when multiple people work on Unity project, someone unaware of this problem could disable important initialization that is defined in parent which could cause unwanted behavior that is hard to debug.

It seems to me that this goes against principles of OOP since you can mess a lot of things on other places. You wont even see a warning in Visual Studio, when trying to do this.

public class A: MonoBehavior
{
  void Awake()
  {
    // Do some stuff
  }
}

public class B: A
{
  void Awake()
  {
    // This actually overrides stuff that Awake() does in parent class
  }
}

Upvotes: 3

Views: 2455

Answers (2)

Hbarna
Hbarna

Reputation: 435

I think sealing the Awake() method from your class A should be what you are looking for:

public class A: MonoBehavior
{
  public sealed override void Awake()
  {
    // Do some stuff
  }
}

Now when you try to override this method in your class B it will not only give an IDE warning but it will not compile.

Upvotes: 1

ChoopTwisk
ChoopTwisk

Reputation: 1334

Solution is simple and adheres to the principles of OOP. Any class you think could have children in the future, define in it stubs

protected virtual void Awake() {}
protected virtual void Start() {}
protected virtual void OnEnable() {}

...list goes on.

Now if someone to use any of the callbacks in a child without 'overriding' the IDE will certainly notify them that there is a base implmentation of the callback.

Upvotes: 2

Related Questions