I know i can do it this way
IEnumerator XXX(){
yield return new WaitForSeconds(5);
Audio.play();
}
And then In Update(){
if(! AudioisPlaying){
StartCorutione(XXX())}
What if i wanted to invoke methiod from Collision.
Is there a way to skip all that nonsense with Corutines in C#?
There are several ways to have actions take place after a period of time. Coroutines are a flexible way to achieve it. You’ll see another poster here suggest behavior trees for everything. Then there are more complex ways that involve threading or timers or private fields and update methods.
However, the simplest way to invoke a method after a delay is probably with Invoke. See Invoke - Unity Learn for more information.
First, please use tags.
Second, for how you’re using the WaitForSeconds, Invoke will probably be the route you’ll want to take. It’s simple, and doesn’t require much change.
Third, and this is just for clarification purposes, but WaitForSeconds can ONLY be done in a coroutine.
IEnumerators aren’t nonsense. They are an amazing concept introduced to C#. However, if you want to invoke them more elegantly you can use extension methods or lamdba expressions:
public static class Extensions {
public static IEnumerator CreateCoroutine (Action action, YieldInstruction yielder) {
yield yielder;
action();
}
public static Coroutine Invoke (this IEnumerator routine, MonoBehaviour mono) {
return mono.StartCoroutine(routine);
}
}
Extensions.CreateCoroutine(() => YourFunction(), new WaitForSeconds(5f)).Invoke(this);
You can save the coroutine that is returned so that you can terminate it if you ever want to.