Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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! 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading