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.
It’s a good post, except 1 little thing: the Random.Range is lower inclusive, and upper exclusive with integers. Eg: do not subtract 1 from the length.*
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”
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.
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”