Add tags during runtime?

Hi so I have a program that dynamically instantiates... "many" objects. With that given, I would like to interact with every object through tags. Therefore I cannot create 1000s of tags for every possibility in the tag manager.

How do add a tag to the tag manager through JS dynamically so that in the next line I could assign that tag to the GameObject?

Thanks

The scripting reference doesn't say anything about accessing the tag manager through code, so I suspect you can't. And as you've probably noticed, if you do something like this:

tag = "no-such-tag";

then Unity throws an exception.

There is of course GameObject.Find to find objects by name. The documentation indicates you shouldn't use this every frame, but rather cache the result or use FindWithTag.

So if you can't use tags, because you have too many, and if you can't keep around GameObject references (why not?), you could implement your own caching scheme.

Create a `Dictionary`. When you instantiate new objects give them unique names and cache them in the dictionary. Then you can look things up in the dictionary by name.

Something like this (in C#) ... note that if you don't manually add your objects at creation time they will automatically be added when you try to find them.

using System.Collections.Generic;

public static class GOCache
{
    static Dictionary<string, GameObject> sGOCache = new Dictionary<string, GameObject>();

    public static Add(GameObject go)
    {
        sGOCache[go.name] = go;
    }

    public static GameObject Find(string name)
    {
        GameObject go;
        sGOCache.TryGetValue(name, out go);

        if (go == null)
        {
            // If not in cache then try and find it.
            go = GameObject.Find(name);
            if (go != null)
            {
                Add(go);
            }
        }

        return go;
    }
}

Realistically, you don’t need thousands of tags for thousands of objects. I used to do this in my earlier games, and broke out of it. Used newer systems.

I use tags created in the Editor, but to tell the difference between all objects I instantiate, say via the creative menu, or dropping an Item, I attach a tag named Interactable, then a small shell script with an Identifier.

So an Identifier would look like this 0|WoodItem|Icons/Wood|True
Meaning the ID,Name,Icon Image Location, and if it is flammable.

When I need to read the data from the tag I use string.split(new char ‘|’) and split it into a string array and do stuff with the data.

A system like this can be extended very well to suit your needs, though I like (@yoyo)'s approach.

-CausticLasagne