- Home /
Loading component by superclass.
Is there a way to load a subclass by a given superclass.
For example I have these two classes:
class SuperClass : MonoBehaviour {
}
class SubClass1 : SuperClass {
}
Then I have a game object prefab which has SubClass1 on it, and I want to get any component that inherits from SuperClass (so in this case SubClass1): gameObject.GetMostSubComponentBySuper();
Object.FindObjectsOfType() will do what you want. Then just cast the result array elements from Object to SuperClass.
This returns all Objects of the given type that are active in the scene. One must also check if the found script is also in the correct GameObject when using this method.
True, I'll unmark $$anonymous$$e as an answer since yours is the better solution.
Answer by Jamora · Jan 23, 2014 at 10:34 PM
GetComponents() will return an array of any class that is the specified type. Derived classes are, by definition, also the type of their superclasses. Thus gameObject.GetComponents();
will return any SuperClass and SubClass1 Components found on the GameObject. You can then iterate over the array and pick any and all elements which meet your requirements.