Home > Mobile >  How to stop a method with a method inside it?
How to stop a method with a method inside it?

Time:12-30

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?

enter image description here

CodePudding user response:

Let the CooldownCheck method return the stop status, e.g., 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; } 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, i.e., it leaves the method at this point and continues to run the caller, i.e., 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.

  • Related