- Home /
C# How to assign tag to GameObject at runtime?
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?
Thanks a bunch to anyone that replies.
You could use Array or List ins$$anonymous$$d of tagging your GameObjects.
Take a look at this post that explains how to create Array and List in C#
Answer by fafase · Sep 08, 2013 at 06:36 AM
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.
Answer by alearso · May 29, 2014 at 09:30 PM
You can do it as long as you define your tag in the "tag list" first. this way you can change back and forth between different tags.
GameObject clone = new GameObject();
clone.gameObject.tag = "myNewTag";
Answer by amit- · Aug 04, 2018 at 09:13 AM
this.gameobject.tag="newTag";
script must be assign to player or object.
Answer by GregoryFenn · Aug 04, 2018 at 01:54 PM
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(); }
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613113755im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Detect a gameObject's tag via OnCollisionEnter() 5 Answers
Nothing Happens at OnTriggerEnter ? 3 Answers
Array elements change Gameobject.tag 1 Answer
Help with string to gameObject.name 2 Answers
Activate/deactivate all GameObjects with same tag c# 1 Answer