# Question about Random.Range and distance.

I would like a ‘certain action’ to happen once the player walks a certain (but random) distance. My code is…

``````    public float distanceTravelled = 0;
Vector3 lastPosition;

void Start()
{
lastPosition = transform.position;
}

void Update()
{
distanceTravelled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;

if (distanceTravelled == Random.Range(0, 10))
{
//Certain Action.
Debug.Log("Yay!");
}

}
``````

The problem is nothing happens between the range of 0 and 10. Any help would be appreciated, thank you!

I see 3 problems here.
First, Random.Range(0,10) returns integer value which won’t match distanceTravelled without some magic. Specify it to get random float by Random.Range(0f,10f).

Second, you are getting random values every frame and that won’t help you to make it deterministic. Save the random value and change it after use.

Finally, you wish to compare equality of float point numbers. Even in a perfect scenario where float point accuracy does not kick in, if the step from the last frame is too large, it will overshoot. distanceTravelled < random < distanceTravelled + movement in this frame will be a problem.

Problem 1, you can just ignore it if you change the comparator to “>=” while saving random value.

Thank you Revolute. Got it working!

``````    public float distanceTravelled = 0;
Vector3 lastPosition;
public float number;
public float maxRandom, minRandom;

void Start()
{
lastPosition = transform.position;
number = Random.Range(minRandom, maxRandom);
}

void Update()
{
distanceTravelled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;

if (distanceTravelled >= number)
{
//Certain Action.
Debug.Log("Yay!");
}
}
``````

In case anyone else needs it.