I’ve been working a lot in Unity lately, so I thought I should probably do a few tutorials on scripting in the game engine. One of the biggest helps I’ve gotten in scripting for the game engine (in which I use C#) is a nifty API function Unity provides that allows me to get all the objects with a specific type, i.e. game objects with a specific script attached. Since this is a quick tip, lets skip the behind-the-scenes and logic, and get to the code already!
MyScript myScriptObjects = FindObjectsOfType(typeof(MyScript)) as MyScript;
This specific function returns a System.Object array of all the Game Objects which have the script MyScript applied. We then cast it so we can get a strongly typed array from the get-go. From here you can access each of these objects in a loop, store them in a generic, etc. Very useful indeed!
Basically the FindObjectsOfType is the same as FindObjectOfType, however, it is probably more useful in most cases I could see it being used since it works with array’s. A good use of this is to perhaps obtain values from each script and add them to a dictionary or list so you can use them, since performing operations en masse could be done just as easily with tags, etc.