Thursday, September 5, 2013

Unity Helper Methods #4: InvokeInSeconds

/// <summary>
/// Invokes an action after waiting for a specified number of seconds
/// </summary>
/// <param name="waitSeconds">The number of seconds to wait before invoking</param>
/// <param name="invoke">The action to invoke after the time has passed</param>
public static IEnumerator InvokeInSeconds(float waitSeconds, Action invoke)
    yield return new WaitForSeconds(waitSeconds);

Typical Usage

Now I know that Unity already has its own Invoke method but Unity's method only accepts a string specifying the method name.

I wrote this method to be able to specify an anonymous lambda instead of the string.

Note that the method's return type is IEnumerator since it yields, therefore we must invoke it with StartCoroutine.

StartCoroutine(InvokeInSeconds(0.5f, () => Destroy(gameObject))); // Destroy the gameObject in 0.5 seconds