So i’ve got a base class that inherits from MonoBehaviour. Then I’ve got class which inherits from that base. Now i’m struggling with initialisation, normally done with the Start() method. But Start() is never called on the base class because an instance of it never actually exists, its only ever derived from. And Start() is never called on the class which inherits from base, is that because it’s not a direct descendant of MonoBehaviour? Anyone know what I should do?
public class BaseMode : MonoBehaviour
{
void Start()
{
// this never calls because BaseMode is never instantiated
}
....
public class Mode : BaseMode {
void Start()
{
// this isn't called when Mode is instantiated
}
// In your base class
protected virtual void Start()
{
}
// Then in my derived class I do this:
protected override void Start()
{
base.Start(); // call base class
}
Regarding my OP, turns out that I actually am getting Start() called in “Mode : BaseMode” class, which is good news, because the code you posted wouldn’t work if that was the case.
What’s interesting is that although Start() will not call by itself in the base class, OnEnable and OnDisable will… meaning, i don’t have to do:
public override void OnEnable()
{
base.OnEnable(); // this is not necessary, OnEnable works in base class
Seems odd that it works for one MonoBehaviour method and not another.
Odd, though it’s likely Unity is just grabbing the first matching method name that comes up through reflection to account for the random preferences when calling methods.
I’ve had random luck with overriding start/awake/update - so what I do is this:
public class BaseMode : MonoBehavior
{
void Start() {
Init();
}
protected virtual void Init() {
// DO INIT STUFF IN HERE
}
}
public class Mode : BaseMode
{
protected override void Init() {
// DO INIT STUFF IN HERE
Base.Init();
}
}
It adds a function call, but on Start/Awake that makes no difference.
That’s odd; I can’t recall ever having to do that, though I’ve been on and off working with Unity for the past couple of years. Hoping someone from UT can chime in on this.
I don’t think you really have to for Start/Awake at least. I’ve been doing it like that a long time, originally I think I started doing it because like Matkins I found the behavior inconsistent between some of the reflection-driven functions (like OnEnable/OnMouseDown) and figured it would be better to just never depend on it instead of trying to keep track of which works what way.