简体   繁体   English

如何用其中的方法停止方法?

[英]How to stop a method with a method inside it?

Basically, I want to break the method if it's on cooldown.基本上,如果它处于冷却状态,我想打破该方法。 But when I move the if statement inside a method, it will not work.但是当我在方法中移动 if 语句时,它将不起作用。 The return keyword will just return to the previous method and continue the rest. return 关键字只会返回上一个方法并继续 rest。 Is there any way to do it?有什么办法吗?

在此处输入图像描述

Let the CooldownCheck method return the stop status, eg, through a Boolean:CooldownCheck方法返回停止状态,例如,通过 Boolean:

public void Interact()
{
    if (CooldownCheck()) {
        InInteract.Invoke();
        lastCooled = Time.time + cooldown;
    }
}

private bool CooldownCheck()
{
    if (lastCooled <= Time.time) {
        Debug.Log(stuff);
        return true;
    }
    return false;
}

Btw., your else { return; }顺便说一句,你的else { return; } else { return; } makes no sense, as any void method has an implicit return; else { return; }没有意义,因为任何 void 方法都有隐式return; at its end.在它的末端。 The return-statement does not stop anything, it returns from the method, ie, it leaves the method at this point and continues to run the caller, ie, the caller will then execute the next statement. return-statement 不停止任何事情,它从方法中返回,即,此时它离开方法并继续运行调用者,即调用者将执行下一条语句。

A way to interrupt the caller as well would be to throw an exception.中断调用者的一种方法也是抛出异常。 But this seems not appropriate in this case.但这在这种情况下似乎不合适。

You can use a goto label tag or a break/continue您可以使用 goto label 标签或中断/继续

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

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