What about e.g.
// for more flexibility rather use an array
// You should also add the ability to change it via the Inspector
[SerializeField]
private float[] lanes = new []
{
7.25f,
2.45f,
2.4f,
7.3f
};
// pass the index of the lane to your method
// this way you can handle all lanes with a single method
private void SwitchToLane(int index)
{
Debug.Log($"Switching to lane {index}", this);
// Get the float at given index in lanes
var x = lanes[index];
var targetPos = new Vector3(x, 0, 0);
transform.position += (targetPos * speed * Time.deltaTime);
if (transform.position.x <= -x)
{
var newPositionLeft = new Vector3(-x, transform.position.y, transform.position.z);
transform.position = newPositionLeft;
}
// Rather use 'else if' when it is already clear that only one case can be true at the same time
else if (transform.position.x >= x)
{
var newPositionRight = new Vector3(x, transform.position.y, transform.position.z);
transform.position = newPositionRight;
}
}
and then call
// Call this to switch to any random lane
private void SwitchToRandomLane()
{
// generate a random int between 0 and lanes.Length - 1
// second parameter is EXCLUSIVE!
var random = Random.Range(0, lanes.Length);
SwitchToLane(random);
}
Further notes:
You would also need to somehow change your condition check in Update
. Currently as soon as the player goes once below the distance threshold you switch lane every frame!
You would probably want to somewhere store the current lane index so when SwitchToRandomLane
is called the current index is excluded from the options and you can only definitely switch to a different lane then the one you are already on.
Both points I leave to you.