简体   繁体   中英

How can I make the "do" loop continue, but not infinitely in my code?

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: :)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM