Will this break my while loop?

I am wondering how to break out of the while loop if the distance is <=3. if the if statements distance is <=3 within the while loops if statement block, will this end the entire while loop? I tried looking this up on many pages but all the answers are very confusing to me.

IEnumerator DogWhistle()
        {
        //if(set == true)
        MoveSpeed = 7.0f;
        //move = true;
        DogAnimation.SetTrigger("runing fast");
        //dist < 12  &&
       while (dist >=3)
        {
            transform.LookAt(Player.transform);
            transform.position = Vector3.MoveTowards (transform.position, Player.transform.position, MoveSpeed * Time.deltaTime);
            yield return new WaitForSeconds(0.0f);
            if (dist <= 3)
            {
                DogAnimation.SetTrigger("idle");
                rotateDog.rot_speed_y = 0;

                PauseForTreat ();
                break;

            }
        }
   
    }

A break should do it, but I think it is best practice to just design your check in your while loop itself to work without having to use a break, for example in case you change your code later to include nested loops.

IEnumerator DogWhistle()
        {
        //if(set == true)
        MoveSpeed = 7.0f;
        //move = true;
        DogAnimation.SetTrigger("runing fast");
        //dist < 12  &&
       bool endLoop = false;
       while (dist >=3 && endLoop == false)
        {
            transform.LookAt(Player.transform);
            transform.position = Vector3.MoveTowards (transform.position, Player.transform.position, MoveSpeed * Time.deltaTime);
            yield return new WaitForSeconds(0.0f);
            if (dist <= 3)
            {
                DogAnimation.SetTrigger("idle");
                rotateDog.rot_speed_y = 0;

                PauseForTreat ();
                endLoop = true;

            }
        }
   
    }
1 Like

In most cases putting the conditional in the loop is the better option.

But sometimes you need something more powerful. break and continue are both useful keywords here. break stops the loop altogether. continue stops the current iteration and jumps to the next one.

If you are really desperate you can use goto. goto is quite powerful if you need to break out of a lot of deeply nested loops.

1 Like

Thanks guys, don’t know why i didn’t think of a conditional.