Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    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,294
    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!