Last active
February 22, 2023 13:32
-
-
Save mstfmrt07/741a51a3ee771d3a55c7d9d973293319 to your computer and use it in GitHub Desktop.
A simple C# extension to easily create WaitForSeconds coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks 🚀🚀