Teleport Your Player to Certain Points In Your World!
Objective: Every time the player starts the game, they are generated to a random point in space that is a part of an array.
We can break down this goal in several, smaller steps.
Step #1 Create an array of 5 positions.
We start out by creating a handle in our script. All the Vector3’s will start zeroed out. We will update it later to be an array of all random points in space within a set range:
[SerializeField] private Vector3[] positions = new Vector[5];
Step #2 Write a method to generate a random index in the array.
We can do this by creating GetRandomIndex. We create a local int called index and set it to be a random integer between 0 and 4, since Random.Range’s first parameter is inclusive and the second parameter is exclusive. We then return index:
[SerializeField] private Vector3[] positions = new Vector3[5];
private int GetRandomIndex() {
int index = Random.Range(0, positions.Length);
return index;
}
Step #3 Create another method to set the position to that index/element in the array.
This is simply done by creating SetPosition which does not pass in any parameters and doesn’t have a return type. We just want to set the player to one random Vector3 position in the positions array. This script is attached to this player object.
private void SetPosition() {
transform.position = positions[GetRandomIndex()];
}
Step #4 Ensure every element (Vector3) in the array is a different point in the world that makes sense.
We can do this by using a for loop in Start to iterate through the whole array and set each Vector3 to be a random point in space. Each random point needs to fit within the plane in our scene while ensuring the player stays on the plane. For this, we make sure y always equals 0.
We call SetPosition() and it sets the position to one of the just generated points in space from the array.
void Start() {
for (int i = 0; i < positions.Length; i++)
positions[i] = new Vector3(Random.Range(-14, 15), 0,
Random.Range(-14, 15));
SetPosition();
}