Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

What am I doing wrong? (problem with classes)

Discussion in 'Scripting' started by smurftra, Jan 31, 2018.

  1. smurftra

    smurftra

    Joined:
    Jan 16, 2018
    Posts:
    9
    Example:

    Class Animal : MonoBehaviour{
    public void Talk(){
    Debug.Log("Animal.Talk");
    }
    }

    Class Dog : Animal{
    public new void Talk(){
    Debug.Log("BARK");
    }
    }

    Class Cat : Animal{
    public new void Talk(){
    Debug.Log("MEOW");
    }
    }

    Class Test: MonoBehaviour {
    protected Animal animal;
    public void TestTalk(){
    animal.talk();
    }
    public void SetAnimal(Animal _animal){
    animal = _animal;
    }
    }


    So i set my animal in class Test with an object i created as a Dog.:

    Dog dog = new Dog();
    Test.SetAnimal (dog);

    I call TestTalk. I expected the result to be a log of BARK. Instead i get Animal.Talk.

    The goal was to have a dictionary of animals, and calling the Talk function on each, and have different results depending on what kind of animals they are.

    What am I doing wrong?
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Having the same function name "Talk" doesn't magically link together the function calls between base and derived types- in order for that to happen, you need to define Talk in the Animal class as virtual or abstract- virtual meaning it's possible for derived types to override that function, and abstract meaning derived types must override that function. You then have to actually override this function in derived types in order for the behaviour to be any different.

    In other words, when a Dog is referenced as an Animal, you lose access to all fields, properties, and methods specific to Dogs until if/when you cast that object back into a Dog, with the notable exception of properties and methods that are virtual/abstract and then overridden.

    Also, please use code tags when posting code here, as shown in the sticky thread at the top of every forum. It's very important.
     
  3. smurftra

    smurftra

    Joined:
    Jan 16, 2018
    Posts:
    9
    Thank you! This fixed it. I will use code tags next time, wasn't aware of it sorry