Commonly used methods/functions in Unity (1): Timing or delaying calling methods/functions

foreword

When working on a project, I encountered a situation where a method (function) was called after a delay for a period of time before calling another method. I found that unity itself has a way to solve this problem, so the records are as follows:

MonoBehaviour.Invoke

public void Invoke (string methodName, float time);

The above description is from the official website API description.

You can use the Invoke method directly when using it. The first parameter is the name of the method to be called, and the second parameter is the time to delay the call, in seconds.

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        Invoke("LaunchProjectile", 2.0f);
    }

    void LaunchProjectile()
    {
        Debug.Log("111");
    }
}

 The meaning of the above script is to call the LaunchProjectile() method with a delay of two seconds after starting the project, and so on. Invoke can be nested in other methods, such as delaying calling another method after calling one method, which can achieve an effect similar to the standby screen saver (Play after a period of inactivity)

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        Invoke("LaunchProjectile0", 2.0f);
    }

    void LaunchProjectile0()
    {
        Debug.Log("111");
        Invoke("LaunchProjectile1", 2.0f);
    }
    void LaunchProjectile0()
    {
        Debug.Log("222");
    }
}

Other similar methods include:

MonoBehaviour.InvokeRepeating

public void InvokeRepeating (string methodName, float time, float repeatRate);

The method is called after  time seconds  methodName , and repeatRate every second thereafter.

NOTE : This function has no effect if the timescale is set to 0.

 

MonoBehaviour.CancelInvoke

public void CancelInvoke ();

Cancels all Invoke calls on this MonoBehaviour.

MonoBehaviour.IsInvoking

public bool IsInvoking (string methodName);

Are there any pending  methodName calls? returns a boolean value

References:

[1]  UnityEngine.MonoBehaviour - Unity Script API

Guess you like

Origin blog.csdn.net/qq_41904236/article/details/130876417