- Home /
Can't call derived class function from list of base class. Ideas?
I've looked all over but cant find anything about how to fix this. How do I get the Foo function to call the overridden function from derived?
class Base : MonoBehaviour{
public virtual void Foo(){
//Something
}
}
class Derived : Base{
public override void Foo(){
//Something else
}
}
class BaseController : MonoBehaviour{
List<Base> L = new List<Base>(); // This is filled with bases and deriveds
void Update(){
foreach(var i in L){
i.Foo(); // Only calls foo from base class
}
}
}
Ideas?
EDIT: Fixed typos
you need use class Derived : Base
you are using class Derived : $$anonymous$$onoBehavoir
Sorry, I do have that. Fixed it above, still wont call like I want it to though.
check if i is really Derived and not Base only using a Debug.Log(i.GetType().Name)
.
BTW: You probably want "$$anonymous$$onoBehaviour", not "$$anonymous$$onoBehavoir"
I don't even need to test this as i know it will work, at least as you written your example here on UA. If it doesn't work for you, there has to be something different in your actual code.
$$anonymous$$eep in $$anonymous$$d that:
each $$anonymous$$onobehaviour class need to be placed in a seperate file with the filename matches the classname
those classes should be public. (when you simplify your code for your question make sure it actually represents your case. You seem to have many "typos" which doesn't help to find your problem)
the method in the base class has to be either virtual or abstract in order to be able to be overridden. Likewise you have to use the "override" keyword in the derived class.
So there's no problem in the code you (currently) posted so there's (currently) nothing to answer here.
Answer by Landern · Nov 09, 2016 at 06:27 PM
Derived isn't inheriting from Base, you're deriving from MonoBehaviour, it should look like:
class Base : MonoBehaviour {
public virtual void Foo(){
//Something
}
}
// Derived should inherit from base which also inherits from MonoBehaviour.
class Derived : Base {
public override void Foo(){
//Something else
}
}
class BaseController : MonoBehaviour {
List<Base> L = new List<Base>(); // This is filled with bases and derives
void Update(){
foreach(var i in L){
i.Foo(); // Only calls foo from base class
}
}
}