When to identify an object using tags as opposed to its name?


Júlio Rodrigues ·

When should I identify an object by its tag rather than its name? — this is a common question. I've asked something equivalent of that several times while I was still learning the main ideas behind Unity scripting.

Before jumping into the main idea of the article, here's a little controversy—the best food for the bored soul. Some people say that tags are in Unity only for beginners, that you should only use components (custom scripts), enums and other more traditional programming tools.

But this is not a consensus by any means. This becomes apparent when there's a need to create a game core for other people to use, like game & level designers. It's a way to force them to be tweaking and refactoring code as they create content for the game. They can definitely do that (with some effort and previous training) or ask for your help whenever they want to do changes, far from ideal.

Another argument in favor of using tags is that if you start to rely on the component type to create your content, that is, you're essentially tagging by using classes (empty or not), if you ever need to do a refactor you'll need to work on lots of these checks since now the component type is also data, if you had used tags (that are already only data) you wouldn't end up in this situation.

I'm saying all this because it's sold pretty hard in programming schools that strict object orientation is the way to go, and that creating the perfect taxonomy for your domain will save you and your project, this is a myopic view on modeling, there are several ways to achieve the same and oo is no silver bullet. Yes, I've said it!

Okay, you didn't even know about this war discussion on whether you should use tags or not and you probably reached this article with the intention of keep using them and was just wondering that if objects can have names why bother with tags? Conceptually it's really simple—names identify individual objects and tags identify groups.

What is a tag in Unity?

It's a word (a string) that can be assigned to one or more game objects. But not any word, you need to preconceive a list of words that are available to be used as tags. This is nice because it allows the Unity editor to create a helpful dropdown list of all the available tags in your project.

A tag is a way to create collections, you could have the collection "Coin", the collection "Enemy Projectile", and so on. They are especially useful when dealing with colliders since you'll need a way to distinguish the multiple colliders that might collide with your player character (or any other object that you're interested in handling the collision).

You can also use tags to get references for all the game objects of a certain type (not the C# type, but a type in high-level, game design sense). And why is this useful? Let's say you're creating an enemy spawn manager but you want to manually position your monsters in the scene and have their start positions as the respawn points, if you're doing it without tags you might be tempted to create a GameObject array (or even worse, multiple public GameObject fields) in your script and manually drag and drop each of your enemies to it, which is both time consuming and error prone, instead what you could do is create a tag, apply them to your enemies and them have a script to do something along these lines (hah, I'll keep the unintentional joke)

She's deadly

public class RespawnSystem : MonoBehaviour {

    private Dictionary<int, Vector3> positions;

    // Use this for initialization
    void Start () {
        positions = new Dictionary<int, Vector3>();
        var enemies = <em>GameObject</em>.Find<em>GameObject</em>sWithTag("Enemy");
        foreach (var enemy in enemies)
        {
            positions.Add(enemy.GetInstanceID(), enemy.transform.position);
        }
    }

    private void Respanw(int instanceID) {
        Vector3 initialPosition;
        if (!positions.TryGetValue(instanceID, out initialPosition)) {
            // throw some error
        }
    }

}

And for the canonical collider distinguishment example, always remember to use CompareTag instead of the operator ==, the reason for that being that when using the equality operator we need to use the getter for the .tag property and that returns a new string causing an unnecessary allocation. For more tips like this please see this tutorial from Unity on garbage collection optimizations.

private void OnTriggerEnter(Collider other) {
    if (other.CompareTag(<em>tags</em>.Coin)) {
        // do coin pick up
    }
}

What is a GameObject name in Unity?

It's simply the name you give to your game object. All the components attached to it will have the same name. Usually, each game object in your game will have a unique name, but it's up to you to make that happen. If for programming purposes you need a unique identifier you can use GetInstanceID.

GameObject's names can be used programmatically (inside your scripts) or just as a way for you to identify objects in your scene while using the editor.

Typical uses of object's names

One of the most common uses for object names in Unity is actually not related to gameplay programming but project organization, you can use object's names to better organize your scene and to look for your objects using a search

Searching for ball objects

But of course, if you're not feeling like creating a tag just for a single object and you need to identify it, the name can also be used. But be careful, if you're doing it every frame for lots of objects, then try to stick to tags or integer identifiers, comparing strings will be needlessly more expensive, the same problem we have with the .tags getter we also have for names.

What about GetComponent<T>?

As said in the introduction, you could also create components instead of relying on tags. They are harder to use in terms of UI unless you also spend time creating custom inspectors/editors, but can yield way more flexible designs, as in any kind of engineering work, it's valuable to spend some time evaluating if the more complex way of doing things is worth it, many times it is not. One big pro of doing it this way is that you can have multiple tags if you choose to create custom components for that purpose.

If you're interested in the performances considerations (always a good idea), please check out this great article on the subject (not from us).

Get those constants right

When dealing with any kind of string constants in your scripts it's always a good idea to crate constant references to avoid silly bugs like mistyping the name of the tag. I suggest something like this

public class Tags {

    public const string Coin = "Coin";
    public const string Enemy = "Enemy";

}

When to use which

Is it a group of things? Use a tag.
It's not? Use a name.

If this article was successful, you now have a pretty good idea of the role of tags and names in Unity. If you believe I'm giving bad advice please reach me on [email protected] to public shame me, you can also share the love for the article.

Detailed Unity Tutorials in your inbox

Subscribe if you want to receive articles and tutorials like this one right in your inbox. 

Classify in:
  • tag
  • GameObject name
  • scripting
  • unity
© Bladecast 2018. All rights reserved.