Spawning prefabs randomly in fixed spots

So, I am making a little 2D game where I want rockets to spawn randomly which the player then have to avoid.

I thought of making 10 locations which the rockets can spawn from, as seen in the picture.

How would you choose a random number from 1 - 10, then spawn it in location1 if the random number is 1?

  • Thanks in advance magicians

Hey!

I’d get a public array of Transforms that you can assign in the inspector, then do something along the lines of:

public Transform[] spawnPoints;

Transform GetSpawnPoint()
{
    int locationIndex = Random.Range(0, spawnPoints.length - 1);
    return spawnPoints[locationIndex];
}

If you use spawnPoints.length in Random.Range, regardless of how many locations you set in the inspector, you’ll always have a chance to get one of them.

Hope that helps!

Edit: Added a bit of clarification.

1 Like

It’s a good post, except 1 little thing: the Random.Range is lower inclusive, and upper exclusive with integers. :slight_smile: Eg: do not subtract 1 from the length.*

1 Like

Since all of your spawn positions are children of one object, you can skip the array and just use GetChild().

Vector3 spawnLocation = rocketTransform.GetChild(Random.Range(0, rocketTransform.childCount)).position;
1 Like

How would you write such a code?
I tried using the line you just gave me, but it says “The name `rocketTransform’ does not exist in the current context”

Hey there!

You should try this class.
You will have to attach the RocketSpawner class to a gameobject in your scene and after that you will have to set the RocketPrefab field with your rocket prefab and the available positions to spawn (rocketPositions).
After that, if you will press the key “A” a rocketPrefab will spawn at a random location.
Also, you will be able to call the “SpawnRocket” class whenever you will need to spawn a rocket.

Here is how the scene looks like.

Thanks.

You’d create a variable of type Transform named rocketTransform. Then, drag n drop it in the inspector.
Unless the script is on the parent object, in which case you can simply replace “rocketTransform” with “transform” :slight_smile: