[Unity3D self-study record] A more elegant way for Unity to delay the execution of a piece of code

In unity , it is very common to delay the execution of a piece of code or a method or several methods.

Generally, the Invoke and InvokeRepeating methods are used. As the name suggests, the first is executed once and the second is executed repeatedly.

Look at the definition:

void Invoke(string methodName, float time);

The first parameter is the method name (note that it is in string form), not a more convenient delegate. The second is how many seconds of delay. Execute only once.


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

The second parameter of InvokeRepeating is how many seconds after the delay, and the third parameter is the number of seconds between each execution.


Have you found that these two methods have a disadvantage, that is, you must enter the method name! That is to say, if I want to delay the execution of a certain piece of code, I must put the code in a certain method, and then use this Invoke or InvokeRepeating method to execute it.

In this way, it will be particularly inconvenient to refer to context variables and attributes, and parameters cannot be passed!!! Nima, what is the use of him?


I guess you must have used such a method. That's right, "Synergy" sounds like a pretty fancy name.

Use StartCoroutine to execute a method with IEnumerator as the return value, which is usually used for asynchronous downloads, and other situations that are time-consuming and cannot cause the game to freeze.

There is also a good class WaitForSeconds, yes, it is just a constructor, which is used for delay (delay.........better than Viagra? Better than Cialis?).

Well, no more nonsense, the following is my own delay method, which exists as a static method in a class. A code that can delay a specified number of seconds at any time and anywhere.

using UnityEngine;
using System.Collections;
using System;
public class DelayToInvoke : MonoBehaviour
{
    public static IEnumerator DelayToInvokeDo(Action action, float delaySeconds)
    {
        yield return new WaitForSeconds(delaySeconds);
        action();
    }
}



How to use it?

For example, if I click a Button of NGUI, then

void OnClick()
{
    StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
    {
        Application.LoadLevel("Option");
    }, 0.1f));
}


see it

Application.LoadLevel("Option"); is the code segment that you want to delay execution.

You can write very long. Action, do whatever you want.

Guess you like

Origin blog.csdn.net/hackdjh/article/details/41721831