I’m currently working on a game that has a set number of hiding places around my scene, all of which have the tag “HidingPlace”. At the start of the game, I’m finding all of the game objects with the above tag and keeping them in an array called hidingPlace. From this, I wish to assign the first element of the array the tag of “redGem” to essentially say ‘There’s something actually hiding in me’
I’ve tried to do this by putting the following code into the Start() function of my script.
hidingPlace = GameObject.FindGameObjectsWithTag ("HidingPlace"); //finds all potential hiding places
hidingPlace [0].tag = "RedGem"; //Assigns the red gem to be hidden here.
However from the looks of the debug logs that I’ve set up, it’s assigning the tag RedGem to all of the objects that I’ve got in my hidingPlace array. Anyone have any idea how I can assign the RedGem tag to just one element in the array. Wishing to have this as a randomly generated event with every new game however thought I would start by assigning it myself for testing purposes - which has proven key!
Many thanks in advance for any and all answers / suggestions.
I’ve tried the same piece of script you posted and for me is working perfectly.
The only thing I can think about is that you have not defined both the tags: to be able to change a tag, you need to define both HidingPlace and RedGem as available tags.
using UnityEngine;
public class Test : MonoBehaviour {
void Start () {
GameObject[] list = GameObject.FindGameObjectsWithTag("HidingPlace");
if (list.Length != 0) {
int index = Random.Range(0, list.Length - 1);
list[index].tag = "RedGem";
Debug.Log("Index changed = " + index);
}
}
}
This is the code to assign the second tag to a random tagged GameObject.
Anyway, I’ve noticed that the change is applied in a strange way on the objects found: I think is something related to the inner ID of the object.
If you create a bunch of GameObject and then you will rename some of them in 1, 2, 3, etc. and then you’ll apply the tag “HidingPlace” to them, it is not said that if index is 2 you are applying the tag “RedGem” to the GameObject you named as 1 (or 2).