waitforSeconds is there a way to do it withot IE numerator nonsense

I want to have something simple like in c#

void xxx(){
yield WaitForSeconds(5);
Audio.play();

}

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.

1 Like

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.

1 Like

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.

1 Like