- Home /
How to make sure unique, randomly spawned, instantiated prefabs only spawn once
I have a game with hundreds of unique prefab items that need to be randomly generated into the scene. The problem I'm running into is that I can't seem to figure out how to prevent my spawner from creating duplicates from the array I've generated.
I wrote a bunch of if/else statements trying to compare my random array value but I ran into a chicken and the egg problem where I couldn't compare a the array's int because it hadn't been instantiated yet and I couldn't compare the int because it had already been instantiated.
I also tried to compare names and destroy, and search for the "Clone" tag and destroy (both seem round about - any guidance would be great :)
void Start()
{
myObjects = Resources.LoadAll<GameObject>("Prefabs");
startPosition = transform.position;
}
void SpawnRandomObject()
{
//spawns item in array between position number 0 thru 49
int whichItem = Random.Range (0, 49);
//replace gameObject set with script that gathers prefabs from folder
GameObject myObj = Instantiate (myObjects [whichItem]) as GameObject;
myObj.transform.position = transform.position;
}
//my efforts were something similar to this
void Awake()
{
var clones:GameObject = GameObject.FindWithTag("Clone"));
if(clones)
{
Destroy(clones.GameObject);
}
}
Thanks! :)
Answer by Graham-Dunnett · May 16, 2014 at 01:31 PM
Have two lists, A
and B
. A
contains all the unchosen objects, so starts off like your myObjects
array and B
starts empty. Pick an object from list A
, and move it to list B
. Over time A
will get smaller, and B
will get bigger. When you're done with an object, move it back from B
into A
. (Or, if you never want the object used again, into a new list C
which stores the used objects.)
Thanks, it took me forever to figure this out but it ended up helping me a lot.
Your answer
Follow this Question
Related Questions
generating unique names for prefabs within an array 2 Answers
Instantiate random object from Array 2 Answers
Any way to enabled all GameObjects in an Array List? (UnityScript) 1 Answer
How can I access collider's game objects? 1 Answer
Why can't I pass an array reference to another array variable? 1 Answer