How To Get Game Objects With A Specific Script Attached – Unity

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.

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:

Destroy(myObject.gameObject);

Otherwise you would just be destroying the script.

Feel free to ask me any questions below. Look forward to more helpful tips and articles.

4 thoughts on “How To Get Game Objects With A Specific Script Attached – Unity

    • 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.

      Like

    • 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

      Like

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s