Question by
Cornelis-de-Jager · Sep 01, 2016 at 02:00 PM ·
componentclass
All inclusive getComponent call for all subclasses
Is it possible to do a generic GetComponent call that treats all the subclasses the same or do I have to call every subclass by name?
// Main and sub class structure
Event : MonoBehaviour
Choice : Event
Action : Event
// Current Code
obj.GetComponent<Event> (); // ----> Gets Event
obj.GetComponent<Choice> (); // ----> Gets Choice
obj.GetComponent<Action> (); // ----> Gets Action
// Wanted Code
obj.GetComponent <Event> (); // ----> Gets Sub Class
I am just lookin to clean up my code a bit.
Comment
Best Answer
Answer by DiegoSLTS · Sep 01, 2016 at 02:18 PM
GetComponent works like you want, if you have one component of type "Action" you can get it with:
GetComponent<Event>()
That's how you're probably getting the collider of some object, maybe it has a BoxCollider (a class that inherits from Collider) but you get it with:
GetComponent<Collider>()
Maybe you have more than one Event or Event-derived component in the same object, and GetComponent only returns the first one it founds.