Won't excecute the overwrited function

Hi guys, I’ve got a little problem with custom classes and inheritance.

I’ve got an empty base class, for example

class A{

    public void Acoolfunction(){
       //do nothing
    }
}

but now I’ve made some other clases

that inheritate from this class. Lets give it an other example:

class B : A{

    public void Acoolfunction(){
       Debug.Log("Hello World");
    }
}

class C : A{

    public void Acoolfunction(){
       Debug.Log("Cya World");
    }
}

Now we come to the tricky part:

I need a list that can contain both classes, B and C. So I created an array of A and added B’s and C’s to it. My problem is, that when I try to call the Acoolfunction of my listed classes, he will allways call the function in A, not the functions from B and C that overwrited it.

So I know the problem, but if I remember right it should have worked that way :confused:
How can I get it to actually call the right method and not the parent typ method?

Thanks for any help.

You need to specify that Acoolfunction is virtual and then override it in the subclasses:

class A {

         public virtual void Acoolfunction() {
         }
      
}

class B : A {
      public override void Acoolfunction() {
             Debug.Log("Hello world");
      }

}

If your first class A do nothing why don’t do this :

class A{

    public virtual void Acoolfunction(){
       //do nothing
    }
}

then this for the others :

class B : A{

    public override void Acoolfunction(){
       Debug.Log("Hello World");
    }
}

class C : A{

    public override void Acoolfunction(){
       Debug.Log("Cya World");
    }
}

I think this can work.

Wow, 2 correct answers at the same time, it was a hard choice, who gets the mark for the right answer^^ Thank you both very much, now it is working. Sadly, for object based languages I’m just used to Java, where you can simply name the function the same way to override it^^

Good night guys and thanks again =)