Skip to content

Instantly share code, notes, and snippets.

@mstfmrt07
Last active February 22, 2023 13:32
Show Gist options
  • Save mstfmrt07/741a51a3ee771d3a55c7d9d973293319 to your computer and use it in GitHub Desktop.
Save mstfmrt07/741a51a3ee771d3a55c7d9d973293319 to your computer and use it in GitHub Desktop.
A simple C# extension to easily create WaitForSeconds coroutines
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public static class MonoExtensions
{
public static Coroutine Wait(this MonoBehaviour mono, float delay, UnityAction action)
{
return mono.StartCoroutine(ExecuteAction(delay, action));
}
private static IEnumerator ExecuteAction(float delay, UnityAction action)
{
yield return new WaitForSecondsRealtime(delay);
action?.Invoke();
yield break;
}
}
//Example usage.
public class SampleClass : MonoBehaviour
{
//Delay duration in seconds
private float animationDelay = 2.0f;
public Animator animator;
private void Awake()
{
animator.SetBool("isActive", false);
//This line will call the animate function 2 seconds later.
this.Wait(animationDelay, Animate);
//Or you can keep the coroutine if you want to kill later in your code.
Coroutine c = this.Wait(animationDelay, Animate);
//Kill the coroutine.
StopCoroutine(c);
}
private void Animate()
{
animator.SetBool("isActive", true);
Debug.Log("Animation is now active");
}
}
@yusirdemir
Copy link

Thanks 🚀🚀

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