# How to stop a Random Number Generator

Hi programmers around the world I am having a problem with a RNG. I am starting the random number generator but the problem is that it runs forever and I really need to stop it. Here are the details I am having
a class called

` private void RNGvoid()
{
int number = UnityEngine.Random.Range(0, 9);

``````    randomNumber = number;
}`
``````

I am using this class in a Coroutine which looks like this:

`private IEnumerator RNG() { RNGvoid(); yield return new WaitForSeconds(0); }`

That Coroutine I am using in order to move my enemy in random directions just like in a MMO RPG game where an enemy just goes around in random directions around its spawnPoint. The problem is that beacuse of the RNG it tries to go in one direction one second and the next second it tries to go in another direction so can someone help by telling me how to stop the RNG or maybe help me with some checks in the method where I move the enemy in a random direction. Here is my code for moving the enemy:

`private void EnemyPositioning() { StartCoroutine(RNG()); if (randomNumber == 0) { transform.position = Vector3.MoveTowards(transform.position, respawnPoint.position, speed * Time.deltaTime); } if (randomNumber == 1) { transform.position = Vector3.MoveTowards(transform.position, respawnPoint.GetChild(0).position, speed * Time.deltaTime); } }`

Remember the goal here is to: Either find a way to stop the RNG after generation a number and then starting again or find a way to get the enemy from its current position to the position referred to by the random number.

Note there to little if statements in the EnemyPositioning() method because there is really no use of making the others without making these 2 work.

You should check if your enemy has reached the target position before selecting a new target position.
You donâ€™t need a coroutine for this, you can just use Update().
You should not write duplicate code and it is easy to avoid in this case.

Just call this in Update(). All children of respawnPoint are assumed to be waypoints:

``````Transform target = respawnPoint.GetChild(randomNumber);

// go towards target
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);

// check if we have reached the target and select a new target
if (Vector3.Distance(transform.position, target.position) < 0.01f)
{
randomNumber = UnityEngine.Random.Range(0, respawnPoint.childCount);
}
``````