Polymorphism issue

Here is a quick code for my issue (not correct syntactically, just for an idea)

class Bird : GameObject { virtual string name() { return "ABird"; } }

class Crow : Bird { override string name() { return "ACrow"; } }

now, if i hold a public 'Bird' variable and 'new' it with 'Crow', when i run the game, the variable just acts like a 'Bird' and not 'Crow'. I can not get 'ACrow' if i call 'name()' through that object but just 'ABird'.

i do this all in a class derived from 'MonoBehaviour'.

Am i ignoring any factors that affect polymorphism in unity?


it seems am making it more confusing.. so i created a smallest possible example to explain my issue

//file name: DrawingObjects.cs

using UnityEngine;
using System;

public class DrawingObject : GameObject

{

    public virtual void Print()
    {
        Debug.Log("DrawingObject");
    }

}

public class Line : DrawingObject

{

    public override void Print()
    {
        Debug.Log("Line");
    }
}

//file name: Polymorph.cs

using UnityEngine;
using System;

public class Polymorph : MonoBehaviour

{

    public DrawingObject m_drawingObject = null;

    public void Init()
    {
        m_drawingObject = new Line();
    }

    public void Start()
    {
        m_drawingObject.Print();
    }
}

public class PolymorphClass : GameObject
{
    public PolymorphClass()
    {
        m_component = AddComponent<Polymorph>();
        m_component.Init();
    }
    public Polymorph m_component = null;
}

//when i create an instance of 'PolymorphClass' in editor and run it, its script 'Polymorph' executes a 'Start' method, which ideally call overriden 'Print' of 'Line', but what i see printed is 'DrawingObject' :( kindly see if am making any mistakes here. (not deriving from game object just opens a new issue of its own (how should i place an objects in the editor then?).. but for now i want to know what else is wrong with it)

You cannot and should not derive from GameObject. This functionality has been removed in Unity 3 (GameObject is a sealed class), and this behavior is highly discouraged. You need to think up another way to solve whatever problem you're facing.

(You cannot use both virtual and override. Make your Crow.name "override string name".) [no longer valid; question was edited]

EDIT: moved answer from comment:

The type of an object is always seen as the class used in the variable declaration, not the actual derived class. You can use myBird.GetType() for that, it will return Bird if it's a Bird, and Crow if it's a Crow. msdn.microsoft.com/en-us/library/ You can also use dynamic casting, so "myBird as Crow" should return null for non-Crows, and Crow for Crows.

That is odd. Looking at your code, it should be working with polymorphism. It could be weird things happening due to the GameObject inhertiance, like Spike says.

Have you double checked everything? Have you tried something exactly the same, without inheriting GameObject?