If you’ve ever wanted to grab all of the game objects in your Unity scene with a specific script attached and refer to them in your code, it’s really straight forward and I’ll show you how. This is something I had to occasionally in Puzzledorf, like if I wanted to get all of the moveable game pieces, although be careful you don’t do it too often as that can slow down your game. I’ve written a bit more about optimization here.
How To Do It
You can use a single line of code:
YourScript yourObjects = FindObjectsOfType<YourScript>();
To find all of your objects, use the above line of code, but replace YourScript with the name of your script.
To find a single object, use the following line of code:
MyScript myObject = FindObjectOfType<MyScript>();
How It Works
In the first code sample, we create an array to hold YourScript’s, and then Unity searches for all objects with that script attached and puts them into the array. FindObjectsOfType<>() returns an array, as seen in the documentation.
The second code sample finds only a single object, because FindObjectOfType<>() returns only the first object it finds.
You could replace YourScript with GameObject and get all of the GameObject’s in a scene, or search for Game Objects with any other type of component attached by replacing YourScript in the code.
Things To Bear In Mind
It only finds active objects from your current scene. If an object is disabled at run time, or not in your current scene, it won’t grab it.
Remember also that if you find an object via it’s script, you only have a reference to the script, not the game object directly. To access the Game Object if you want to do something like destroy it, you have to reference the gameObject property specifically, like the following:
Otherwise you would just be destroying the script. Feel free to ask me any questions below.