I’m trying to create and assign a tag to a GameObject so I an access it later on, but discovering that I cannot at run time assign tags to GameObjects created.
For example, if I have a loop that creates 100 GameObjects at run time, and I want to give each GameObject an id of 1, 2, 3, 4 all the way to 100. Then, later on, if I want to update object “49” at run time, how can I access this GameObject if I cannot assign a tag to it through C#?
sudo code:
for(int i = 0; i < 100; i++)
{
Create and instantiate 100 game objects;
object.tag = i.ToString(); //assign object tag
}
Now after, if I want to access one of these gameobjects by the tag, I could just look up the object with “GameObject.FindGameObjectsWithTag()”, or so I thought, but this does not work.
How can I create GameObjects in run time, assign them a unique id, and then later access them?
You cannot create tag at runtime, they are defined in the list and you can only choose from one that is there. Your situation is a little sad since you would have to create all possible tag before hand.
A possible solution would be name them appropriately instead and look by name. Tags are more to group object, like “enemy”, “projectile” or else. As you are using unique tag, this is not good.
All in all, use name instead and look by name. Note that they all receive a instanceID given by Unity but it is just a number and remembering all of them is…well you know.
It’s a shame you can’t just do this ( because GameObject is sealed. Does anyone know why GameObject is sealed? Or a hack-way around it?).
public class GameObjectWithID : GameObject
{
public uint identificationNumber;
public string idTag {
get { return identificationNumber.ToString(); }
}
}