- Home /
Choose a Random Tag
Basically, I have five GameObjects each with a tag that is a number between 1 and 5. I'm trying to set the tagNumber integer = a random integer between 1 and 5. Then, I want it to set the target variable equel to a GameObject with the randomly selected tag. Any help is much appreciated.
 Transform target;
 public int tagNumber;
 
 
 void Awake () {
         tagNumber = Random.Range (1, 5);
         target = GameObject.FindWithTag (tagNumber).transform;
 
     }
or just change it to this:
 tagNumber = Random.Range (1, 6);
 target = GameObject.FindWithTag (tagNumber.ToString()).transform;
Answer by pako · Oct 17, 2017 at 06:36 PM
 GameObject.FindWithTag(string tag) needs a string parameter, not an int.
- Create a string array to hold your tags e.g. - string[] tagsArray = new string[5] //to hold 5 tags
- You can declare the array as public and enter the tag strings in the Inspector, or declare them in the array initializer. 
- Use - Random.Rangeto get a random index for the array e.g. for 5 tags the array length is 5, with indeces 0 to 4. So, use- randomIndex = Random.Range (0, 5) //5 is excluded
- Then: - string randomTag = tagsArray[randomIndex]
- Finally, - target = GameObject.FindWithTag (randomTag).transform
At which point do I declare the "randomIndex" variable?
Sorry I overlooked that. You can declare it inline, i.e. int randomIndex = Random.Range (0, 5);
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                