Home > Back-end >  How can I make the "do" loop continue, but not infinitely in my code?
How can I make the "do" loop continue, but not infinitely in my code?

Time:02-14

Basically, whenever I walk into the trigger it repeats the loop infinitely. I know the reason for this but I don't know the way to fix it so that it works properly. It's meant to do it until you leave the trigger.

public void OnTriggerEnter(Collider other)
        {
            
            InDamageRange = true;
            
            StartCoroutine(waiter());
        }
    
        public void OnTriggerExit(Collider other)
        {
            StopCoroutine(waiter());
            InDamageRange = false;
            
        }
    
        public IEnumerator waiter()
        {
            do
            {
                yield return new WaitForSeconds(1.5f);
                player.Health = player.Health - damage;
            } while (InDamageRange != false);
            
        }

What can I do to make this work?

Edit: Turns out the issue was that I was trying to stop the coroutine before setting the bool to false. I swapped the two lines in OnTriggerExit and that fixed the issue, thanks for the help! :)

CodePudding user response:

Every time you call waiter() you are creating a new instance of your IEnumerator. You do need to keep a reference to the original one if you want to stop it. Try this:

private IEnumerator _waiter;

public void OnTriggerEnter(Collider other)
{
    InDamageRange = true;
    _waiter = waiter();
    StartCoroutine(_waiter);
}

public void OnTriggerExit(Collider other)
{
    StopCoroutine(_waiter);
    InDamageRange = false;
}

public IEnumerator waiter()
{
    do
    {
        yield return new WaitForSeconds(1.5f);
        player.Health = player.Health - damage;
    } while (InDamageRange != false);
}

But given your code setting InDamageRange = true should have also stopped it. Is it your actual code?

  • Related