Stopping a coroutine?

I have been looking around but can’t seem the proper way to stop a coroutine from running. I tried StopCoroutine() but that didn’t seem to work. A little help would be great!

IEnumerator Jump(GameObject target)
    {
        while (true)
        {
            float dist = Vector3.Distance(transform.position, target.transform.position);

            if (dist >= 0.5f)
            {
                transform.position = Vector3.MoveTowards(transform.position, target.transform.position, 2.0f * Time.deltaTime);
            }
            else
            {
                if (isOffTruck)
                {
                    agent.enabled = false;
                    isOffTruck = false;
                }
                else
                {
                    agent.enabled = true;
                    FindClosestPart();
                    isOffTruck = true;
                }
            }
            yield return null;
        }
    }

I would prefer to stop the coroutine when the dist is < 0.5. At that point the gameobject has its own logic to follow.

You could have the coroutine stop itself if you know the conditions for stopping.

if(dist < 0.5f)
   yield break;

Normally, you can save a coroutine in a variable since StartCoroutine() returns that.

Coroutine coroutine = StartCoroutine(...);

And then pass the variable into StopCoroutine().

Otherwise, there’s a way to stop a coroutine inside itself. Try that if you want to do that, but I’m not sure if that’s the correct way:

yield break;

Shows you several ways to stop it. Otherwise, the other post mention how to exit from within the coroutine.

However, in your case, you could simply change your while statement to be

while(dist >= .5f) so once it’s less, it just exits the loop.
Or maybe try a do…while loop.

Wow lots of responses! Lots to try haha, thanks all!

the yield break was what I am looking for. It was the simple solution that always alludes me.

I actually tried changing the while(true) to while(dist > 0.5) but then I didn’t have a good way to update the dist within the coroutine. Hence why I had to change it.

You don’t even need a yield break if you let the code run to the end, then the coroutine will exit. So a break to break out of the while loop would’ve sufficed.

I did this(the StopCoroutine reference) and got a NullRefrrenceException error on the console.

Make your own post, don’t revive a 3 year old post responding to someone who hasn’t been on the forums in a couple of years.