Getting all Objects With the Same Script Attached in Unity

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.


2 thoughts on “Getting all Objects With the Same Script Attached in Unity

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s