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 quite straight forward. You can also get a single game object the same way. Use this:

TileData[] objectsToClear = FindObjectsOfType<TileData>();

In the above code sample, TileData is a script in my project. I create an array of them, and then search for all objects with that component attached. Unity will find all objects with that component in the scene, and turn them into an array.

You could also replace TileData 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 TileData in my code.

Bear in mind, however, it only finds active objects. If an object is disabled at run time, it won’t grab it.

If you have a single object you want to grab with a script, your player for example, you could use this similar function:

PlayerController playerReference = FindObjectOfType<PlayerController>();

This will assign our variable playerReference the object in the scene with the PlayerController script attached. If you have more than one active object in the scene with that script attached, it’ll just get you one of them.

Note, however, that it only retrieves Game Objects active in the current scene. It won’t get prefabs that aren’t instantiated, and it won’t get GameObjects from other scenes that aren’t loaded.

If, however, you do wish to get Prefabs with a specific script attached, there is a way, and I’ll talk about that in a future article.

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

Advertisements

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 )

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