简体   繁体   English

我怎样才能使“do”循环继续,但在我的代码中不是无限循环?

[英]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.编辑:原来问题是我试图在将 bool 设置为 false 之前停止协程。 I swapped the two lines in OnTriggerExit and that fixed the issue, thanks for the help: :)我交换了 OnTriggerExit 中的两行并解决了问题,感谢您的帮助::)

Every time you call waiter() you are creating a new instance of your IEnumerator .每次调用waiter()时,您都在创建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.但鉴于您的代码设置InDamageRange = true也应该停止它。 Is it your actual code?这是你的实际代码吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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