- Home /
Spawn object using vector array anywhere but previous spawn location
I am spawning an object randomly in one of 5 locations using a vector array. How can I spawn another object using the same array anywhere BUT where the previous object was spawned?
The first object is spawned using code similar to this:
var num : int = Random.Range(0,vectorArray.Length);
Instantiate (gameObject, vectorArray[num], transform.rotation);
Now, how can I yield for a certain amount of seconds and then instantiate a second object at random, excluding the previous spawn point (because that object will still be present and don't want objects overlapping).
Answer by rutter · Apr 08, 2012 at 12:26 AM
Probably the quickest method is to keep track of the previous index, and keep generating random numbers until you get one that isn't the same. Not the cleanest fix, but it'll get the job done in a pinch.
Ultimately, you'd probably be better off building a List
or other dynamic structure that allows you to remove values as they're used, but that may be a more complicated solution than you're looking for at the moment.
How would I go about using the first method you mention? How do you generate random numbers excluding a single number?
Something like this:
var lastNumber = -1;
function GetRandom(max : int) : int
{
var num = lastNumber;
while ( num == lastNumber )
{
num = Random.Range(0, max);
}
return num;
}