Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

GetComponent for an inherited class MonoBehaviour?

Discussion in 'Scripting' started by IchBinJager, Jun 28, 2016.

  1. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    So. Let's say I have an Item base class for a MonoBehaviour, and I make a class that inherits from it called tool.cs , can I use GetComponent<Item>() to access it since I may have different classes all inheriting from Item, and just call like say Item.Taken() to call the Taken from the tool class?

    Or would this not work due to how classes work? Or Unity?
     
  2. Trexug

    Trexug

    Joined:
    Dec 2, 2013
    Posts:
    88
    Yes, that will work.

    Unity makes use of this - you can get a 'BoxCollider'/'SphereCollider' of an object by getting the 'Collider' component and you can get a 'SkinnedMeshRenderer'/'MeshRenderer' by getting the 'Renderer' component.

    It is probably obvious, but your base class needs to inherit from 'Component' or a class which inherits from 'Component' (in your case, inheriting from MonoBehaviour probably makes the most sense) for this to work.
     
    eugeneloza likes this.
  3. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    And if I do that but call say like Get_Description() it will do it for the lowest level, like tool? Just checking.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,352
    It works like how inheritance always works; the method is dispatched to the last override of the method.

    So if Tool : Item, and Tool has overridden Taken(), then GetComponent<Item>().Taken() will call Tool.Taken() if the found Item is a Tool.
     
    duhnnie likes this.
  5. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    I got it. I can do base.Taken() or whatever if I need the higher class called. Thanks guys!