class BaseClass : MonoBehaviour {
new void Start() {
Debug.Log("start in base class"); //does not print
}
}
class SubClass : BaseClass {
new void Start() {
Debug.Log("start in sub class"); //prints
}
}
I know that I can define the Start() method as a protected virtual function for override. Just wondering if it’s possible to define the same method in 2 classes with the “new” keyword?
Here is an example I found on the net from a Microsoft MVP that made good sense here
public class A
{
public virtual void One();
public void Two();
}
public class B : A
{
public override void One();
public new void Two();
}
B b = new B();
A a = b as A;
a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B
Override can only be used in very specific cases. From MSDN: You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
So the ‘new’ keyword is needed to allow you to ‘override’ non-virtual and static methods.
In my Sense, Virtual with Override is better they gives you full access over calling methods.
Use base.Start() from child class, when you want something from Super Class, otherwise Child class is doing its work with no issues.
You don’t need new when there is nothing to override.
But in general I would MicroEyes way, using virtual + override, this gives you explicit control and the possibility to call into the base method too which normally is the reason why you have it and use inheritance.
The new keyword is normally only related to so called ‘smells’ as in ‘this code stinks’ and missused to undefine previously implemented functions. Thats required if the base class wasn’t yours but if the base class is yours too you should properly structure the hierarchy from the start instead of using bad practices right away