Tip for Unity users : Yield WaitForSeconds alternative

Hi…

I would like to share a trick to achieve something similar to yield WaitForSeconds from Unity… making pause of the current thread without sleeping the whole thread… This does not sleep the thread but the effect is the same.

Unity coroutine:

IEnumerator Sequence ( ) {
     Do_A();
     yield return new WaitForSeconds(2.5f);
     Do_B();
     Do_C();
     yield return new WaitForSeconds(5.2f);
     Do_D();
     yield return new WaitForSeconds(3.3f);
     Do_E();
}

Unreal coroutine:

void AMyActor::Sequence ( ) {
     float _waitSecs = 0;
     static int _state = 0;
     
     switch (_state++){
     case 0:
     {
          Do_A();
          _waitSecs = 2.5f;
     } break;
     case 1:
     {
          Do_B();
          Do_C();
          _waitSecs = 5.2f;
     } break;
     case 2:
     {
          Do_D();
          _waitSecs = 3.3f;
     } break;
     case 3:
          Do_E();
     } break;
  
     if (_state == 4){
          _state = 0;
          return;
     }

     FTimerHandle _th;
     GetWorld()->GetTimerManager().SetTimer(_th, this, &AMyActor::Sequence, _waitSecs, false);
}

here is what i did. I defined a macro like this:

#define DELAY(seconds, ...) \
{FTimerHandle __tempTimerHandle; \
GetWorld()->GetTimerManager().SetTimer(__tempTimerHandle, FTimerDelegate().CreateLambda(__VA_ARGS__), seconds, false);}

And then i can use it like so:

DO_A();
DELAY(0.5f,[this] {
	DO_B();
	DO_C();
});
1 Like