- Home /
How to randomly instantiate other prefabs parallel?
I'm making this game where you have slide down platforms (that are parallel) but had problems with generation. I made a little script that generates 10 of the same platforms parallel. But how do I randomly instantiate other prefabs? I tried with a random number generator and if statements but then the platforms wouldn't be parallel anymore.
My script:
[SerializeField] private Transform platforGen1;
[SerializeField] private Transform platforGen2;
[SerializeField] private Transform platforGen3;
[SerializeField] private Transform platforGen4;
[HideInInspector] private float nextPlatformYCord = 0f;
[HideInInspector] private float nextPlatformXCord = 0f;
private float numOfPlatforms = 10f;
int x = 1;
private void Awake()
{
do
{
SpawnPlatforGen1(new Vector2(10.33815f, -3.778132f) + new Vector2(nextPlatformXCord, nextPlatformYCord));
nextPlatformXCord += 16.31f;
nextPlatformYCord -= 10.49f;
x++;
} while (x <= numOfPlatforms);
}
private void SpawnPlatforGen1(Vector2 spawnPosition)
{
Instantiate(platforGen1, spawnPosition, Quaternion.identity);
}
Answer by hopper · Jul 21, 2020 at 08:03 PM
One way you could do this is by placing all of your prefabs into an array.
[SerializeField] private Transform[] platformPrefabs;
Then you could create a random number generator to select a random prefab from this group based on the object's index in the array. This range is 0 -> length of array - 1 so we can create our generator in a scalable fashion like this:
Transform prefabToSpawn = platformPrefabs[Random.Range(0, platformPrefabs.length - 1)];
Then just use the instantiate function like you've used above to spawn a random object out of the array.
It's been a while since I used Unity all the time but this should do the job. Here's your code modified to fit this style:
[SerializeField] private Transform[] platformPrefabs;
[HideInInspector] private float nextPlatformYCord = 0f;
[HideInInspector] private float nextPlatformXCord = 0f;
//you were comparing a float to an int so I fixed that, unless you very specifically want to have like 10.5 platforms
private int numOfPlatforms = 10f;
int x = 1;
private void Awake()
{
do
{
SpawnPlatforGen1(new Vector2(10.33815f, -3.778132f) + new Vector2(nextPlatformXCord, nextPlatformYCord));
nextPlatformXCord += 16.31f;
nextPlatformYCord -= 10.49f;
x++;
} while (x <= numOfPlatforms);
}
private void SpawnPlatforGen1(Vector2 spawnPosition)
{
Transform platformToSpawn = platformPrefabs[Random.Range(0, platformPrefabs.Length)];
Instantiate(platformToSpawn, spawnPosition, Quaternion.identity);
}
This works, thanks. I didn't think of an array but definitely will now and I didn't know an integer would show up in the inspector.