- Home /
instantiate a random object from multiples via 'tag'
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:
cont'd from first post. I want to run a loop that instantiates a new random prefab each time the loop fires. I would put my code up, but each time I do, I get what I think is an epiphany, but it never works. LOL. Thanks in advance!
Answer by aldonaletto · Dec 18, 2011 at 04:28 AM
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);
Yeah, that was the first problem. I figured out that 'FindGameObjectsWithTag' only works on objects that are already in the scene after I posted this. I'm trying to Instantiate a prefab, so it won't work because it doesn't exist yet, LOL.
I think your second solution makes sense to me, I'm going to try it once I get home.
Your answer
Follow this Question
Related Questions
multiple object in multiple spawn Point with out repeat 0 Answers
Instantiate prefab with different tag 4 Answers
How to instantiate the first 8 gameobjects in an array (UnityScript)? 1 Answer
My array does not update when object is destroyed. How do I fix it? (java) 2 Answers
Spawning Objects Using An Array. 1 Answer