简体   繁体   中英

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. The return keyword will just return to the previous method and continue the rest. Is there any way to do it?

在此处输入图像描述

Let the CooldownCheck method return the stop status, eg, through a 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; } makes no sense, as any void method has an implicit 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.

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

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