GetComponent for an inherited class MonoBehaviour?

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() 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?

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.

1 Like

And if I do that but call say like Get_Description() it will do it for the lowest level, like tool? Just checking.

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().Taken() will call Tool.Taken() if the found Item is a Tool.

1 Like

I got it. I can do base.Taken() or whatever if I need the higher class called. Thanks guys!