Unity stops calling InvokeRepeating() method

You can use the CancelInvoke() function to stop calling InvokeRepeating(). Examples are as follows:

// 声明一个float类型的变量用来存储调用Invokerepeating()的时间间隔
public float repeatTime = 2.0f;

void Start () {
    
    
    // 在Start()函数中调用InvokeRepeating()函数
    InvokeRepeating("RepeatFunction", 0.0f, repeatTime);
}

void Update () {
    
    
    // 在Update()函数中监听按键操作,按下空格键时停止调用InvokeRepeating()
    if (Input.GetKeyDown(KeyCode.Space)) {
    
    
        CancelInvoke("RepeatFunction");
    }
}

void RepeatFunction () {
    
    
    Debug.Log("RepeatFunction is called!");
}

In this sample code, first call the InvokeRepeating() function in the Start() function to call a custom function RepeatFunction() cyclically, and the time interval is the value of the repeatTime variable. Then monitor the keyboard key operation in the Update() function. If it is detected that the user has pressed the space bar, the CancelInvoke() function is called to stop the call of InvokeRepeating(). Finally, the specific logic is implemented in the RepeatFunction() function, where a piece of debugging information is simply output.

Note: The CancelInvoke() function does not stop the call of InvokeRepeating() immediately, but stops after the current loop ends. If you need to stop the call of InvokeRepeating() immediately, you can use CancelInvoke("RepeatFunction") to specify the specific function name.

Guess you like

Origin blog.csdn.net/weixin_44919646/article/details/129638546