Search Unity

[Solved] GetComponent and Inheritance

Discussion in 'Scripting' started by Thimble2600, Sep 22, 2017.

  1. Thimble2600

    Thimble2600

    Joined:
    Nov 27, 2015
    Posts:
    165
    Hi, short question.
    I have a prefab called Helmet which has a component script also called Helmet that inherits from class Item.
    If I Instantiate Helmet, can I then get the Item class using GetComponent?

    Perhaps this is a rhetorical question because my results say no, but I'm baffled.

    Code (CSharp):
    1.     private void InventorySlot_Equip(GameObject gameObject)
    2.     {
    3.         GameObject t = Instantiate(gameObject);
    4.         //cannot return GetComponent<Item>().m_itemType, probably because Item does not exist? This GameObject has Helmet that inherits Item.
    5.         m_gear.Add(new Gear(t, GetComponent<Item>().m_itemType));
    6.     }
    EDIT Okay I see what I was doing wrong now. In my defence I was tired as all hell. I forgot to get the component from GameObject t. God knows why I didn't think to do that in the constructor for the gear struct. Bah.