- Home /
Parent Start() not being called from base.Start()
I have very straight forward code but I have no idea why my base.Start() is not being called.
Call 1 is logged, Call 2 is not. Can you advise why base.Start() is not calling the parent class?
public class AggressiveBruiser : Personality
{
void Start ()
{
Debug.Log("Call 1");
base.Start();
}
}
public class Personality : Enemy
{
void Start()
{
Debug.Log("Call 2");
base.Start();
}
}
Answer by Bunny83 · May 11, 2015 at 03:32 AM
Your Start method isn't a virtual method and you're not overriding it in the derived class. That means you just hide the method in the base class.
public class AggressiveBruiser : Personality
{
protected override void Start ()
{
Debug.Log("AggressiveBruiser: Start");
base.Start();
}
}
public class Personality : Enemy
{
protected override void Start()
{
Debug.Log("Personality: Start");
base.Start();
}
}
public class Enemy : MonoBehaviour
{
protected virtual void Start()
{
Debug.Log("Enemy: Start");
}
}
The method of course need at least protected visibility to be able to override it. Public or internal would work as well.
I think thats Ugly :( I just made my own Init class and called it from there. Its Ugly because Start() isn't even listed as protected. But thank you this clears it up.
Why is that ugly? That's how inheritance works... If a method isn't virtual you can't override it since there's no v-table in the class.
As in Start is not shown as protected Start() it just appears as Start().
Unity uses reflection to call any of it supported callbacks. Because of that it doesn't matter if it's declared as private, protected or public. That's why it's per default declared as private. Important: The $$anonymous$$onoBehaviour class doesn't declare a Start method which could be overridden. Since Unity uses reflection to call those callbacks it can optimise the callbacks. Unity only calls methods that actually have been declared in the class.
Actually what Unity does is "ugly" in the sense of OOP. Protected is like private but allows derived classes to see and override them. Private methods can't be overridden since they are private. No other class can see / use / override them except the own class.
That's all just common OOP. If a class declares something as private it indicates that it doesn't want a derived class to access it. If a derived class should be able to access a member it has to be at least protected. That's also true for variables.
Answer by phxvyper · May 11, 2015 at 03:33 AM
By default, MonoBehaviour hides inheritance.
You need to define your higher Start function as virtual, so that the base.Start function may be called.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Initialising List array for use in a custom Editor 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Derived Class Fields 3 Answers