how to deal with GameObject class and my custom inheritance

Hi Everybody,

I’m a beginner at Unity and I have a simple problem that drives me crazy! I’m sure it will be answered in an instance.

I just don’t understand how to combine between the GameObject class and my inheritance system.

Let’s say that I was multiple enemies with similar properties (health, armor etc…) but different values.
So I created a base class called “Enemy”, and then a few child classes, “Orc” “Goblin” etc…

I create prefabs for Goblin and Orc, and add the relevant script component.

Now I just don’t get how can I use those Orc and Goblin scripts. Because everything in the Scene is a GameObject, when I try to get the type of the GameObject back I get “GameObject”, not “Orc” or “Goblin”

Let’s say I have a UI image that I want to change depending on which enemy I clicked. If I click on a Goblin I’ll see a Goblin image, and so on. How can I determine with a mouse click which object this is?
If I try to get the Type I get “GameObject”.

That’s my question. How do I recognize the type of the GameObject I clicked on/ How do I know which Script component is attached to it and how to access it from there.

(I saw that in the shooting game Unity created as a demo they created prefabs with public variables, and then inserted the values in the inspector and saved the prefab with those values. I don’t want to do it this way, I want it in code.)

Waiting for your answers, Thanks!

There are two ways to do it:

  1. In your “Enemy” class you can define a property named “Type” of enum type and put all your’s enemies’ types in the enum. Then you can set up you prefab, choosing proper enemy type in editor.

or

  1. Create a prefab for each enemy type and assign corresponding child class to them (“Goblin” or “Orc”). Then in code you can do like this:

    GameObject enemy = …
    Orc orc = enemy.GetComponent();
    if (orc != null)
    {
    // it is an orc, use “orc” variable
    orc.SomeMethodOfOrc(…);
    }
    else
    {
    Goblin goblin = enemy.GetComponent();
    if (orc != null)
    {
    // it is a goblin, use “goblin” variable
    goblin.SomeMethodOfGoblin(…);
    }
    }