Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active March 22, 2024 07:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/0da9a9721c15bd3af1d2ced0a367e24e to your computer and use it in GitHub Desktop.
Save kurtdekker/0da9a9721c15bd3af1d2ced0a367e24e to your computer and use it in GitHub Desktop.
Call After Delay - handy Unity3D coroutine to do something later
using UnityEngine;
using System.Collections;
public class CallAfterDelay : MonoBehaviour
{
float delay;
System.Action action;
// Will never call this frame, always the next frame at the earliest
public static CallAfterDelay Create( float delay, System.Action action)
{
CallAfterDelay cad = new GameObject("CallAfterDelay").AddComponent<CallAfterDelay>();
cad.delay = delay;
cad.action = action;
return cad;
}
float age;
void Update()
{
if (age > delay)
{
action();
Destroy ( gameObject);
}
}
void LateUpdate()
{
age += Time.deltaTime;
}
}
@omundy
Copy link

omundy commented Jun 18, 2022

@kurtdekker I'm curious why you changed from coroutine to the current method?

@ysftulek
Copy link

@omundy @kurtdekker I'm also wondering the same thing. You can have the same behaviour with Coroutines. Callbacks from Update + LateUpdate might be slower too compared to the pure boolean comparison of Coroutine in Update (I suppose it's running in Update, although I'm not sure).

@gakkossphynx
Copy link

why not coroutine ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment