What is the equivalent of Coroutines in UE4?

Hi guys, I come from Unity3D. A coroutine in Unity is a way to execute a specific code every frame without putting the code in the Update() function which in UE4 is the Tick() function. Is there a way to implement such behavior in Unreal?

1 Like

Not in C++. The language doesn’t really support it in a cross platform way, like some platforms implement a ‘Fiber’ which is a native coroutine. Blueprints sort of support coroutine style scripting, in that some of the nodes automatically are executed over multiple frames without you needing to worry about it. It just executes the next node when the previous node in the chain finishes, similar to how a coroutine allows for arbitrary yield/resume. (for example the Delay Node)

If you’re executing the same code every frame, you’re better off just putting it in Tick. If you need a state machine around it, just having a switch statement that executes a different case base on an Enum state is my preferred approach to mimic a coroutine flow in C++.

Cheers,
Nick

1 Like

Thanks for the redirection, I didn’t see the duplicate question.

Checkout the class I made for courtine/async style programming: Utility class for asynchronous/coroutine style programming in UE4 C++ · GitHub
It doesn’t do multi-threading and only intended to be be used with methods that take longer than one frame to execute (play animation, move to, open UI Widget and wait for it to be closed, etc).

It only works with functions (delegates), that accept callbacks as their parameter.
It’s very easy to write your own Async methods that run Unreal’s MoveTo, PlayAnimation, etc.
I can provide examples if you’re interested.

Old Question but I thought I would provide an approach I use that has the same effect. If blueprinting, create a custom event in the Event Graph. Perform whatever scripting you want and then add a delay node. This delay node acts like a co-routine, as it won’t prevent the rest of the event graph from processing. Co-routines are something I do miss from Unity/C# workflow.

This answer is a little bit too late for you I guess :slight_smile: But I was just googling for the same question and this came up; so for anyone else wondering about the same problem I would suggest an alternative.

Instead of using the OnTick event (which is equivalent to Unity’s Update) I suggest that you use a Timer or Timeline event.
I can’t really tell you much about Timelines so you’ll have to check that out, but here’s a solution that might work for you regarding Timers:

You create a trigger for which to call the Timer Event, and you set it to update by a loop which uses DeltaTime. But because the Timer Event itself will only be ran once you have to make sure that the function you are calling can pause and clear the timer itself!
Check out the examples in my images, hope it helps!

There are also Timers. I use them a lot :slight_smile:

Please visit the link below if you are interested in yet:

For those who is still looking.
Here is the most effective and lightweight solution how to achieve a similar result like it is in Unity’s coroutines (no timers, no delay nodes, no timelines, not inside tick with a bunch of checks). In Unreal the same functionality is easily achieved by using Latent Actions.

In order to make it happen and to use it in your blueprints, you will need to write a code in C++. The best example is to look at how Delay node is made. But instead of a counting down a variable, you should just call TriggerLink() in Update. Here is an example of how a final node looks like in my blueprint:

266223-2019-01-22-23-57-18-starfortressarpg-unreal-editor.png

To have Update/Finished nodes you need to use enum and expand it in meta. Result - is an object that controls your coroutine (so you can stop it when it is needed).

	UFUNCTION(BlueprintCallable, Category = "GameBPLibrary", meta = (Latent, LatentInfo = "LatentInfo", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject", ExpandEnumAsExecs="Exec"))
		static void RunCoroutine(UObject* WorldContextObject, ECoroutineStateExec &Exec, struct FLatentActionInfo LatentInfo, UCoroutineActionResult *&Result, float &DeltaTime);

This may not be really related but… Do you know how to make the hierachy link centered in the top like yours do?

hm… what do you mean?

Hello My friend,
Could you show me how your script looks like? I tried to recreate it but I’m stuck.
Is UCoroutineActionResult just an Object?

I think the best alternative is Timer with lambda and callback. In this example I play three sounds one by one in sequence to simulate weapon reload and on completion I run Callback()

bool UCreature::LoadWeapon( UCreatureWeaponObject* Weapon, TFunction<void()> Callback )
{
	AsyncSound( PrimaryWeapon->CreatureWeaponObjectTable.MagOutSoundCue );
	GetWorld()->GetTimerManager().SetTimer( EngageTimer, FTimerDelegate::CreateLambda( [&, AmmoUnit, Weapon, Callback]
	{
		AsyncSound( PrimaryWeapon->CreatureWeaponObjectTable.MagInSoundCue );
		GetWorld()->GetTimerManager().SetTimer( EngageTimer, FTimerDelegate::CreateLambda( [&, AmmoUnit, Weapon, Callback]
		{
			AsyncSound( PrimaryWeapon->CreatureWeaponObjectTable.CockingSoundCue );
			GetWorld()->GetTimerManager().SetTimer( EngageTimer, FTimerDelegate::CreateLambda( [&, AmmoUnit, Weapon, Callback]
			{
				Weapon->LoadAmmo( AmmoUnit );
				if (Callback)
				{
					Callback();
				}
			}
			), Weapon->CreatureWeaponObjectTable.CockingTime, false );
		}
		), Weapon->CreatureWeaponObjectTable.MagInTime, false );
	}
	), Weapon->CreatureWeaponObjectTable.MagOutTime, false );
	return true;
}

Usage:

LoadWeapon( PrimaryWeapon, [&] { FunctionToCallOnFinish(); } );

In Ue5
I recommend this plugin GitHub - landelare/ue5coro: A gameplay-focused C++17/20 coroutine implementation for Unreal Engine 5.

Its very easy to use!

2 Likes