Findgameobjectswithtag



This OnAwake method will find all of the GameObjects with the target tag, then loop through them caching their transform in the possible targets array. The possible targets array is then used by the overridden OnUpdate method. Tags must be declared in the tag manager before using them. A UnityException is thrown if the tag does not exist or an empty string or null is passed as the tag. Note: This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject. FindGameObjectsWithTag ('CheckPoint'); Now we create the ' ActivateCheckPoint ' private function that will active the current checkpoint and disable the rest. // Activate the checkpoint.

Finding and referencing a game object properly in Unity3D is one of the most asked questions for those who are new to Unity3D. In this article, I will write about referencing game objects, finding them according to their names, tags, and types. But let me give you the answer to the question at the title briefly.

In Unity3D, we can find game objects according to their names, tags, and types. For these purposes, we use the following methods respectively: GameObject.Find( ), GameObject.FindWithTag( ) and Object.FindObjectOfType(). These methods will return only one game object. Additionally, it is also possible to find all the game objects that have the same tag or are in the same type, using GameObject.FindGameObjectsWithTag( ) and Object.FindObjectsOfType( ). These methods will return arrays of game objects.

Contents

  • Referencing game objects in Unity3D

Referencing game objects in Unity3D

What is referencing?

Findgameobjectswithtag

Most of the time, we want to access other game objects and their components. Hence, we can gather information about them when it is required, send information to them, control their behaviors, or execute a method that is in a script that is attached to them. In these cases, we need an address(or let’s say a phone number) of the game object and thus, we can dial whenever we want. This is called referencing.

While developing games in Unity3D, we always reference other game objects or components. Therefore, this is a fundamental topic you should understand before you go further.

How to create references to game objects or components

First of all, we have to declare variables that will store the address of the game objects or components. And hence, whenever we would like to access the properties of these game objects or components, we use these variables.

In the code above, we declared two variables in type GameObject but we have not assigned any object them yet. You may consider this as if we are reserving empty rows in an address book that we will fill them out later.

To reference these variables, we have a couple of options. We can search the game object that we want to assign using built-in methods that are included in Unity. We will see this option in later sections of this article. Another option is to assign relevant game objects directly in the Unity editor. But to do this we have to declare the objects either public or private with [SerializeField] attribute.

In the code above, the first variable is declared as private(you can put the private keyword in front of it as well if you want), the second variable is declared as public and the third variable is declared as private with [SerializeField] attribute. [SerializeField] attribute makes this variable visible in the editor but still inaccessible from other scripts.

Now, you can drag and drop the game objects, that you would like to assign, to the slots that are visible in the inspector.

If you would like to create references to the components that are associated with the game objects, you need to declare variables that are in the type of that component.

How to find game objects by their names

As I mentioned above, we can create references to game objects and components by searching and finding them using built-in methods in Unity. This is useful especially when you want to stay the variable private or when you want to access an object that is created during runtime.

In order to search for a game object that has a specific name in the scene, we have to use the method GameObject.Find( ). It takes a string parameter. And this parameter is the name of the game object that we want to find.

In the code above, we created a reference for the game object that has the name “Sphere”.

Not

If you would like to access a component that is attached to this game object, you should create a reference for that component. For instance, the following creates a reference for a rigidbody component that is attached to this game object, and hence you can access the properties of this component.

Finding a game object that has a specific tag

In addition to finding an object by its name, we can also find it by its tag which we are able to determine objects in the scene.

To find a game object that has a specific tag, we use the method GameObject.FindWithTag( ). This method takes a string parameter and searches for it (There is one more method that does the same job. You can also use GameObject.FindGameObjectWithTag( ) for the same purpose).

A tag can be used either for only one object or multiple objects. If there is more than one object that has the same tag, this method returns only one of them.

Getting the array of all game objects that have the same tag

If there are multiple objects that have the same tag and we want to get them all, we need to use the method GameObject.FindGameObjectsWithTag( ). Likewise, this method also takes a string parameter and returns an array of all game objects. Therefore, we have to declare an array that will store the game objects.

The following returns and assigns all objects that have the tag “Cube”.

Finding a game object that matches a specific type

Transform

We can also search and find a game object that matches a specific type. In other words, for instance, we can get a game object or component that has a specific component. To do this, we use the method Object.FindObjectOfType( ). This method also returns only one of the objects.

The following one finds a light component and creates a reference to it.

Getting the array of all game objects that match a specific type

If there are multiple game objects that match a specific type, we can find all of them and create references in an array. For this purpose, we use the method Object.FindObjectsOfType( ). This is an example of how we use it:

How to find a child game object

In order to find a child object and create a reference to that child object we can use the method Transform.Find( ). This method takes a string parameter and returns the child game object that the name matches this parameter.

Assume that there is a game object in the scene that has a tag “Player”. And also assume that this player object has a child game object which has the name “Gun”. If we want to create a reference for the “Gun” object, we may do this as the following:

This is useful especially if there are multiple objects that has the same name under different objects.

Further remarks

In this article, we see different ways of how we reference game objects in Unity3D. Here, I need to warn you that searching and finding methods are extremely slow and you should avoid using them in Update, FixedUpdate, or LateUpdate methods, if possible. We generally use them in Start or Awake methods. You may also consider creating references in Singleton’s to improve performances. We have various tutorials about the Unity3D Engine that you can see in this link.

What's the best way to use GameObject.Find?

This is one of the easier answers I like to give on the forum: You don't. Ever.

One of the most reliable indicators of newbie code in Unity is the presence of GameObject.Find. It's nearly ubiquitous in newbie code but utterly nonexistent in runtime code written by more experienced programmers, for three reasons:

  1. It's really easy to figure out how it works and make something work, quickly.
  2. It works in a wide variety of situations.
  3. There is always, absolutely, without exception, a better option available to accomplish the same task.

It's attractive to newbies because learning one function call lets you get a lot of things done pretty quickly. However, relying on GameObject.Find will cause a lot of problems in the long run - performance problems, reliability problems, false positives and false negatives. The larger your game gets, the more significant GameObject.Find's problems will become.

Plus, all the cool kids will make fun of you for using it.

So what is it about GameObject.Find that's so bad?

Speed: When you call GameObject.Find, Unity crawls through every single GameObject in the scene, comparing its name to the string you're searching for. By computer science standards, this is agonizingly slow - imagine trying to find a book in a library that's not alphabetized or sorted by Dewey decimals, for example.

Findgameobjectswithtag

Reliability: There are far too many things that can go wrong when using GO.F without being noticed right away. Forgot to capitalize one letter in either the object name or the function call? Error. In older versions of Unity, the engine would actually add (Clone) to the end of an instantiated GameObject's name - that would've broken it. This isn't a concern anymore, but any code (e.g. on the Asset Store) that was written for older versions of Unity that expected that? Error. But the most common issue for reliability is duplicate names. If you ever have a second object that has the same name as the one you're looking for, there is absolutely no way to know which of those objects it's going to find. And when it finds the wrong one? Error.

Worse, all of those errors are runtime errors, not compile time errors. That means that they don't show up when you write the code, only appearing when you start playtesting the game. In some cases, they only appear when you playtest extensively, finding that unusual edge case where a second object named 'Score' can appear at the same time when you hit two blocks in quick succession.

No Code Complete: MonoDevelop, or your script editor of choice, can't possibly know what your GameObjects' names are when you're writing code, so it can't autocomplete them for you the way it can class and function names.

'But it's cool if I only use it in Start(),' I hear you say. Right?

No.

Don't get me wrong. Limiting GO.F usage to Start() is definitely better than calling it every frame, or (yech) multiple times per frame, in the same sense that I'd much prefer to be stabbed in the eye once as opposed to getting stabbed in the eye 60 times a second for the next hour. It's faster, true. But really, the performance considerations of GO.F are not the only reason to avoid it, and limiting its usage to Start() does nothing to absolve its reliability issues.

What's the magic word I should use instead?

The only problem with replacing GameObject.Find is that there's not a single technique you replace it with. There are, in fact, probably dozens. The good news is that most of them aren't very complicated, and you only really need to learn five or six techniques - between them, these techniques should cover all the situations in which you may have previously been tempted to use GameObject.Find.

Each technique is described here in terms of speed, reliability, and versatility, but keep in mind that each one also covers a specific range of purposes.

GameObject.FindWithTag

GameObject.FindWithTag is a slight improvement on .Find. Rather than using the name of the GameObject, it uses the tag (which can be set just under the name field in the Inspector). It also has a sister function, FindGameObjectsWithTag, that will find all the objects with the given tag, good for groups of similar GameObjects.

Speed: FindWithTag is faster than .Find, because Unity creates a Dictionary of all GO's that are tagged - a Dictionary lookup is far faster than the 'look through each object one by one' method employed by GameObject.Find, especially if you have a lot of objects. It's not the fastest technique listed, but only barely. You'll still need to call GetComponent after using this, which is not ideal, and many of the other methods get around that.

Reliability: FindWithTag is slightly more reliable than .Find, but this area is its biggest weakness compared to the other methods we'll discuss. It does reduce the likelihood of typos causing issues, but that's about it.

Versatility: The tag system in Unity is pretty limiting, largely in the fact that you can only apply one tag to a given GameObject. Maybe you can make your red team tagged 'Red' and your blue team tagged 'Blue', but then all the players on both teams are just done for tags. You can't then use the tag system to find your goalies, for example. The non-trivial chance that two schemas for tagging will collide ultimately seriously limits the usage of FindWithTag.

Overall, FindWithTag is probably the worst replacement for GO.F on the list. However, its speed and relative simplicity does make it worth keeping in your toolbox, even if it's used sparingly.

Public member assignment via Inspector

Ultimately, this is one of the Unity fundamentals that you're absolutely going to have to learn. A public variable can be assigned in the object's Inspector by drag and drop. It's best used for objects that have a logical relation to each other - a character might have a reference to his own weapon, for example.

Speed: Super-fast. Essentially instant, in fact. And you can use the exact type of component you need, too - if you find yourself calling target.GetComponent<Character>(), then you can make your target a Character instead, and avoid the GetComponent call altogether! Anything derived from UnityEngine.Object can be drag-dropped this way, most notably all Components (including Camera, Renderer, etc), and all MonoBehaviours (and by extension, all of your own scripts). One side note: someComponent.transform is faster (and slightly more reliable) than someTransform.GetComponent<SomeComponent>(), so opt for linking directly to the SomeComponent instead of the Transform (or the GameObject) when you have the option.

Reliability: Very reliable. When you drag and drop a reference into the object, you know it's going to be that one, specifically. No ifs, ands, or buts about it. The main catch to keep an eye on is that references from inside a prefab to outside of it, or between two different scenes, might get broken.

Versatility: As described above, this technique is best used on objects that not only have a logical relationship to each other, but a hierarchical relationship as well (although that's far from a solid rule).

Opportunistic Assignment

Ultimately, this technique is very similar to the previous technique, and has far too many ways to be made useful to hope to list them all here. Fundamentally, all it means is: when you have access to the thing you need, hold onto it and store it. The most common use cases involve collisions and raycasting, I think, but it can apply almost anywhere.

If used in combination with other techniques on this list, it can become very powerful indeed. For example, if ScriptMaster uses GetComponentsInChildren<ScriptSlave> to loop through its children, it can set ScriptSlave's 'master' property to itself, and now every slave knows who its master is.

The main difference between this and assignment via inspector in terms of code is that your code will have to be written in such a way that this object being null doesn't cause errors, which usually means simply putting null checks as seen above - make sure it fails gracefully until the object has a valid reference.

Storage Upon Instantiation

It seems to have escaped the notice of many a rookie Unity programmer that Instantiate returns the object that it has spawned, meaning it can be assigned immediately (and reliably) upon creation. I've seen many a piece of code where Instantiate is immediately followed by 'something = GameObject.Find' for the very object that was just created. Such a waste!

I find this comes up a lot with intermediate programmers who are trying to code their first grid system as well, say for a puzzle game. Store the grid cells you've created in an array (it can be multidimensional if need be), and you'll always have quick, reliable access to them!

Speed: Instant, with the caveat that you'll need to use GetComponent to access particular components.

Reliability: As long as the reference to the original object is good, this will be, too.

Versatility: Obviously only useful when you're instantiating things.

GetComponentsInChildren

This function is extremely useful for objects that are in a hierarchy. It'll catch all of a specific class within the hierarchy of a particular object. If you do need to filter these for whatever reason, you can still apply your own filtering logic when you go through them.

Speed: Not superfast, but option the fastest you can do for the sort of situations it's used for. Take advantage of caching!

Reliability: Very solid.

Versatility: Extremely useful for stuff within a hierarchy.

Singleton

(The above is an extremely barebones implementation of a singleton; see the dedicated article on singletons for more complete versions.)

Singletons are one of those programming tools that are so useful and simple, you actually have to be careful not to use them too much - which is the only reason this technique is so far down this list. A singleton is a static reference to an object that is the sole instance of a given class in a scene. In other words, it's a single object that's accessible from anywhere. If this sounds extremely useful and the answer to all of your problems, that's exactly what it is! ...until you realize three months from now that you need a second instance of the Player class because you're adding network support, and now you're in trouble because you've written singletons all over the place, and it no longer makes sense.

So I'll say this once: A Singleton is best used when there can only logically be one of that class in existence. Generally, the best time to use a singleton is for the user interface. A few other good examples of singletons are manager classes, network connectivity management, and so on. You can use them to access the player character too, but be cautious when doing so - it's really easy to get trapped and make it impossible to add network play or AI opponents without significant rewrites.

Speed: Instant.

Reliability: If implemented as it is above, good but not great; there are a number of edge cases in which you can get snagged on a null reference. However, if implemented correctly, a singleton can be absolutely rock-solid. See the singleton article for more information.

Versatility: As stated, you should only use this if there will only ever be one of something. But if there are more than one, and you want something similar? Read on!

Multiton (maintained static list)

(The above is an extremely barebones implementation of a multiton; see the dedicated article on singletons/multitons for more complete versions.)

Findgameobjectswithtag

So you like the idea of a Singleton, but you have more than one thing? No problem! The multiton is a list that objects add and remove themselves to and from as they are created and destroyed. Just like a singleton, the multiton's list is available anywhere, anytime.

Unity Findgameobjectswithtag

Speed: Not quite as fast as a singleton, but very close - only slower because you may need to loop through them. Still pretty much instant, though.

Reliability: Just like the singleton, it depends on the implementation. Above is the simplest and least reliable example, but the article about them will have examples of a much better implementation.

Versatility: Definitely more versatile than a singleton, especially because it doesn't rule out other techniques in the process. You can have a list of all characters readily available via Character.all, but still opportunistically assign them during collisions, for example.

Findgameobjectswithtag Transform

FindObject(s)OfType

FindObjectsOfType is a useful method to find all of a given class in the scene. There's not much more to it than that.

Speed: It's worth keeping in mind that this method is slow - potentially slower than GameObject.Find, even. If you find yourself calling this more than once or twice in a scene, you're probably better off with a Multiton as described above, if you're able. Thus, this method is most commonly used on classes to which you're not able to add your own OnEnable/Disable methods to, such as the builtin Unity classes.

Reliability: The main advantage that this has over GO.F is that you know exactly what you're getting back from it.

transform.Find

If you absolutely, positively have to find something by name, then use transform.Find. But first, be really, really sure you absolutely have to find it by name. Are you sure you can't attach a component to the child, and find it with GetComponentInChildren? Are you sure you can't make a public reference, and assign it to that? If so, use one of those other methods.

In my experience, just about the only time this is truly necessary is when you need to find an object in the hierarch of an imported 3D object - for example, the location of where the camera should be for that cinematic scene you set up in Blender.

transform.Find is essentially what GameObject.Find would be if it were limited to one hierarchy instead of the whole scene. Because it's limited to one hierarchy, it's more reliable (less concern about false positives), more versatile (you can still use it if you have more than one copy of the thing in your scene), and faster (fewer objects to check). You can even include the entire hierarchal path to the transform you want in order to be sure that you get that specific one.

Unity's documentation on transform.Find contains good information and code examples.

Related Sidenote: SendMessage and BroadcastMessage

I don't see SendMessage or BroadcastMessage much these days, but they're worth mentioning here in any case. SM and BM have much of the same appeal and the same drawbacks as GameObject.Find - they're easy to understand, but slow and imprecise and error-prone. (If any other script adds a function named TakeDamage that doesn't mean exactly the same thing as the TakeDamage function you've already written, you run the risk of calling the wrong one.) And, indeed, many of the above solutions would be very handy for replacing SendMessage and BroadcastMessage, in particular GetComponentsInChildren.

There's one additional tool in the chest for replacing these, and that is interfaces. An interface is, quite simply, a description that you apply to a class saying, 'This class implements these particular functions, and they are available for your use.' By using an interface, the compiler knows that you want the Enemy class and the Player class to both have a TakeDamage function that can be called when a bullet hits their collider, but that TakeDamage function has no chance of being confused with another function that is coincidentally named TakeDamage down the line.

Interfaces are 'inherited' kind of like classes, so to distinguish them from classes, they conventionally start with an 'I'. Interfaces can be used in GetComponent calls, for convenience. (According to the documentation, interfaces can not be used in FindObjectsOfType calls.)