Get *ALL* components in a GameObject

I’ve been digging through the forums for this for hours, it’s totally time to just ask lol:

All the component grabbing functions unity provides require a Type parameter, which makes them useless when you want to get back every component attached to the gO.

My reasons for doing this are to be able to get all components out of an object that are a subclass of a particular type. I can’t find any snippets on doing this anywhere in particular. Here’s what I have:

public static ArrayList GetComponentsOfType<T>(GameObject o) where T : class {
	
	Component[] objs = o.GetComponents();  // if only, if only i could just leave this parameter list blank
	
	ArrayList goodObjs = new ArrayList();
	T com;
	
	for (int i = 0; i < objs.Length; ++i) {
		com = objs[i] as T;
		if (com != null) {
			goodObjs.Add(com);
		}
	}
	
	return goodObjs;
}

Is there a gap in my knowledge, or am I screwed?
Cheers

1 Like

I think there is a gap in your knowledge, if I understand you correctly.

You can just do:

GetComponents(typeof(Component));

To return a static array with all components on a GameObject. If you want all components that are subclasses of something, just get the parent class:

GetComponents(typeof(Fruit));

Will return an array that includes all of your Apple, Orange, Pear, etc components.

P.S. I think that typeof() syntax is correct for C# (we use JS daily).

5 Likes

Oh. Really?! I swear I did test that. Thankyou so much for the quick response, i’ll go hang my head in shame now (: