Use all variables from array (in Random.Range())
So, I've got a simple code for 2D game, which spawns random objects on 11 spawn locations. There are 4 type of objects in GameObject [] array. This is the function for spawning:
public Transform[] spawnPoints;
public GameObject[] blockPrefab; // four of the objects,with different colors that get spawned and fall.
void spawnBlocks()
{
for (int i = 0; i < spawnPoints.Length; i++)
{
Instantiate(blockPrefab[Random.Range(0,4)], spawnPoints[i].position, Quaternion.identity);
}
}
There's one problem with this code. The player can only go through the "Block" whichever has the same tag as player's color(player's color changes from time to time). Sometimes the the block appropriate tag doesn't spawn and passing through is impossible. So I want to know, how's it possible to spawn all type of block in this code - Instantiate(blockPrefab[Random.Range(0,4)], spawnPoints[i].position, Quaternion.identity);
-Thanks for help!
Answer by tormentoarmagedoom · Jul 13, 2018 at 10:18 PM
Good day.
You can create a bool array called "BlockCheck" with
BlockCheck.lenght=number of block types
And generate the random number before instantiate
int RandomNumber = Random.Range(0,4)
while (BlockCheck[RandomNumber] == true)
{
RandomNumber = Random.Range(0,4);
}
Instantiate(blockPrefab[RandomNumber ], spawnPoints[i].position, Quaternion.identity);
BlockCheck[RandomNumber] == true;
So it will be randomizing numbers until find one that is still "aviable".
For complete the loop, just need to create a "if" to detect when all elements in bool array are true, to reset them all to false.
Bye!!
Answer by nikacr7 · Jul 14, 2018 at 06:26 PM
Or can I just spawn 4 different type of cubes on 4 different spawn locations? That would be helpful as well.
Your answer
Follow this Question
Related Questions
List or Arrays, and how to randomize them. 1 Answer
How do I check for random range which is divisible by 2 2 Answers
What range of values need to be inserted if we need to pull a random item from the list? 0 Answers
Add force random movement and random rotation [2D] 1 Answer
Object spawn at spawn points 1 Answer