Join the Discord. Talk about Game Dev. Talk about Gaming.
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.
So, how do you get an object with a specific script attached ?
Use the line of code I gave you to get all objects with a script attached:
TileData objectsToClear = FindObjectsOfType();
Except replace ‘TileData’ with the name of your script.
Or, to get a single object, use the other line of code I gave you:
PlayerController playerReference = FindObjectOfType();
but replace ‘PlayerController’ with the name of your script
It doesn´t find the game object, i put a destroy function right after that line and instead of destroying the game object it just destroys the script.
If you’ve found your object by it’s script, when you go to destroy it, you have to go Destroy(script.gameObject);
You have to specifically reference the game object the script is attached to.