- Home /
Randomize a spawn position without repition
How can I randomize an x and z coordinate from 1 to 10 and then remove that x and z coordinate from the 100 possible combinations? like if i do this
public List<int> xSpawn = new List<int>();
public List<int> zSpawn = new List<int>();
public Rigidbody fallingBlockPrefab;
private Rigidbody fallingBlockInstance;
void Start()
{
StartCoroutine("SpawningBlocks");
for (int a = 0; a < 10; a++)
{
xSpawn.Add(a);
zSpawn.Add(a);
}
}
IEnumerator SpawningBlocks()
{
yield return new WaitForSeconds(SpawnTime);
int randX, randZ;
randX = Random.RandomRange(0, xSpawn.Count);
randZ = Random.RandomRange(0, zSpawn.Count);
xSpawn.RemoveAt(randX);
zSpawn.RemoveAt(randZ);
fallingBlockInstance = Instantiate(fallingBlockPrefab, new Vector3(randX, 20, randZ), transform.rotation);
fallingBlockInstance.name = "FallingBlock " + numberSpawned;
StartCoroutine("SpawningBlocks");
}
but it still spawn duplicates in. So basically say once a cube has spawn at position x=2 and z=3 I don't want it to spawn at position x=2 and z=3 but still be possible to spawn at x=2 and say z=2 if it makes sense.
Answer by RoyaleNite · Mar 09, 2019 at 02:54 PM
I made a for loop from 10 to 110 to and then split it into x and z according to the position
for (int a = 10; a < 110; a++)
{
string spawnLocation = a.ToString();
if (spawnLocation.Length == 2)
{
spawnPosition.Add(new SpawnPos((int.Parse(spawnLocation[0].ToString())), (int.Parse(spawnLocation[1].ToString()))));
}
if (spawnLocation.Length == 3)
{
spawnPosition.Add(new SpawnPos(int.Parse(spawnLocation[0].ToString() + spawnLocation[1].ToString()), int.Parse(spawnLocation[2].ToString())));
}
}
then just random a number from 0 to 110 and use that number of the list then just remove it afterwards
int randX, randZ, index;
index = Random.RandomRange(0, 110);
Debug.Log(spawnPosition[index].xPos + ";" + spawnPosition[index].zPos + "Number : " + index);
randX = spawnPosition[index].xPos;
randZ = spawnPosition[index].zPos;
spawnPosition.RemoveAt(index);
Answer by misher · Mar 09, 2019 at 12:34 PM
Create one single list with all possible positions.
Shuffle the list
Create a queue from the shuffled list
Dequeue a position when spawning
Recreate a new queue if needed
Answer by oroora6_unity · Mar 09, 2019 at 11:22 AM
You are using the index of the list for the position. Instead, you should use the value that you are removing in the coroutine.
he means
xSpawn.Remove(randX); ins$$anonymous$$d of RemoveAt
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Randomize 2 clips from an AudioSource List by name? 1 Answer
Public list are not reflecting in inspector. 1 Answer
How to make Random.Range() step by a certain amount? 1 Answer
Checking a list containing another list, and checking if the elements in the list are equal problem 1 Answer