I need a run-time script that will find all instances of a given component. I know how to do this with an editor script, but the components I’m looking for may (or may not!) be in a prefab, instantiated at run time. So I want to do something akin to GetComponentsInChildren, but for the ‘root’ of the scene. Is that possible?
http://unity3d.com/support/documentation/ScriptReference/Object.FindObjectsOfType.html
Generally, I want that to be a generic function, instead of one that returns Object, so I use extension methods to clean up the code a bit:
using UnityEngine;
public static class ExtensionMethods {
public static T FindObjectOfType <T> (this Object unityObject) where T : Object {
return Object.FindObjectOfType(typeof(T)) as T;
}
public static T[] FindObjectsOfType <T> (this Object unityObject) where T : Object {
return Object.FindObjectsOfType(typeof(T)) as T[];
}
}
Then, in any class that derives from UnityEngine.Object (such as a MonoBehaviour), you can do
Whatever[] arrayOfWhatevers = this.FindObjectsOfType<Whatever>();
Sure just use FindObjectsOfType. It does exactly what you want