I have been researching and trying to figure this one out to no avail. I have 4 different objects with the tag “PlayerPawn”. I want to instantiate a random object from the ‘FindGameObjectWithTag’ list/array. I’m not sure how to accomplish this. I’m thinking:
The question isn’t totally clear, but I suppose you want to get an array of PlayerPawn tagged objects (prefabs or scene objects) and clone a randomly selected element, like this:
... var objects = GameObject.FindGameObjectsWithTag("PlayerPawn"); var newObj = Instantiate(objects[Random.Range(0, objects.length)], pos, rot); ...
But creating an array of PlayerPawn tagged objects with FindGameObjectsWithTag isn’t a good idea. This function only finds scene objects, not prefabs. You may, of course, place the 4 different PlayerPawn objects in your scene in the Editor, and use FindGameObjectsWithTag to fill an array with them - but do it only in Start; if you use FindGameObjectsWithTag during program execution, the other objects already instantiated will enter the list as well. This will result in one of them being more and more frequent than the others - the more the object is instantiated, the more it will appear in the array, increasing its probability in being instantiated again - not to mention that it will terribly slow down your game.
A better solution would be to create a public array and assign the PlayerPawn prefabs to it in the Inspector:
var objects: GameObject; // drag the prefabs here at the Editor ... var newObj = Instantiate(objects[Random.range(0, objects.length)], pos, rot);