[Tutorial] Creating and Using Delegates C++ and Accessing them in Blueprints

**Before we start: **
A disclaimer I do not pretend to be an expert but i do my best in trying.
So if any mistakes are made in this tutorial I please let me know so I can fix them that and feedback in general is much aprichiated.

What will we learn in this tutorial:
In this tutorial you will learn how to create and use a delegate in Unreal Engine 4.
And making them available in Blueprints.
Using C++, i will try to keep this as explaining as i can leaving out any complicated examples or wall of code.

What is a delegate?
A technical explanations is available on the Documentation. (See reference link at the bottom.)
But broken down a delegate is a event that is Brodcasted / Ā«SendtĀ» in your game.
These can be picked up by other classes / Actor in your game, variables can also be included so you have a copy of the data.

Note: In this tutorial am using a copy of the value, i thought that made the code look simpler.
But please note that you should pass any data with reference when possible to save memory.

Now lets get coding:

The first thing you want to do when creating a delegate is go to the header of the class you want the delegate to be Broadcasted from.

Over your class deceleration, you will want to declare your delegate.
e.g: Over this.



/**
 * 
 */
UCLASS()
class YOUR_API AYourGameState : public AGameState
{
	GENERATED_UCLASS_BODY()


You do this by using the following macro.



DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGameStateTimeOfDayChanged, float, Houer, int32, Minute, int32, Sec);


The above code declares a new delegate with the name and 3 parameters.
The Ā«FGameStateTimeOfDayChangedĀ» is the delegate name Ā«typeĀ» and the the following are the data types and there names devide by a comma Ā«,Ā».

e.g: You want to make a delegate to pick up a chat string from a team chat in-game, this would at least need 2 FString`s one for the player name that sendt the message. And one for the actual message sendt to the team in-game.

You would declare the following delegate.



DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FTeamMessageSendtDelegate, FString, PlayerName, FString, Message);


Notice: Make a note of that the end of the delegate declaration changed from _ThreeParams to _TwoParams For a full overview on all the variations check out links at the bottom, but it lets the engine know how many you/ it needs.

Now we have our delegate and there are only two things left to do for creating them.
First we go and add a new member to your class, its worth to mention that delegates donā€™t belong to the class. So there is no reason for not using the same delegate in a second class as long as it has its own member in that class.

We declare the new member for the delegate like this.



public:
	UPROPERTY(BlueprintAssignable)
		FGameStateTimeOfDayChanged OnTimeUpdated;


The BlueprintAssignable is used, so that it can be used with Blueprints.
Now the only thing left to do is to have the class Broadcast the delegate with the data.
In your class at some point you want to tell some other class that something happend like in-game time was changed in your game state.

You Ā«sendĀ» the event like this.



	// Broadcast Delegate 
	OnTimeUpdated.Broadcast(CurrentHouer, CurrentMinute, CurrentSeconds);


CurrentHouer, CurrentMinute, CurrentSecond are members in my game state class, that the delegate belongs to. And are of type float, int32 and int32 this is the dala values Ā«sendt with the delegateĀ».
remember we used BlueprintAssignable with the member so we can use it with blueprints already.
But maybe you want to use it in code as well so then we can do the following, for this last example i am using a delegate with only one value a float.

So in your Ā«secondĀ» class that you want the delegate to be Ā«picked upĀ» you need to create a callback function for that so we create a new function in our second class.
Important: Copy the signature perfectly and add that to the function deceleration.

For Visual Studio users, right click on the delegate in VS and select/ mark the delegate name Ā«FDelegateNameĀ» and right click and press Ā«Go to DefinitionĀ» to jump to the delegate signature. Or by pressing Ā«Ctrl+Alt+F12Ā»
Untitled.png

e.g: OnMinuteUpdate declaration looks like this.



// Used for getting the Time of Day on the map Min(0.00), Max(23.59).
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGameStateSigleTODChanged, float, Houer);


So in our Ā«second classĀ» we add a new function like this.



	UFUNCTION()
		void BindToDelegate(float houer);


Notice we have the same type and name from the delegate.
Now all that is left is to bind the new callback function to the delegate.



YourGameState->OnMinuteUpdate.AddDynamic(this, &AYourGameMode::BindToDelegate);


You use this line of code for that, note that Ā«YourGameStateĀ» is the game state of your game that has been cast to your game state. So that you can find the new delegate member, adding Ā«bindingĀ», this function to the delegate can be done in several places but ::BeginPlay() is a easy place to bind the delegate as you know your actor is in the world by then.

Blueprints: The only thing you need to do to use this with Blueprints is get the class / object.
Search up the name of the delegate and add it to the graph.

Conclusion: By now i hope you have a good understanding of delegates and know how to use them.
And also how to make them available in blueprints.
In a later tutorial we will look at how we can have these callback functions or delegates be replicated over the network for multiplayer games.

**Reference: **

Please leave feedback, PDF download available .
For reading on the go.

Best Regards.
.

6 Likes

Not sure why no comments yet, but thanks for the excellent writeup =)

2 Likes

You are welcome :), glad someone liked it.

Nice tutorial.

Very useful

With some cleaning up and formatting, I thnk you could post this in the tootorial wiki

Great tut. Keep up the good work.

Thanks.

You are welcome glad you liked it.

Sure i never added anything to wiki before so i need to read up on that stuff.
What parts should be cleaned up btw ? :slight_smile:

Hi! Thank you for this write-up :slight_smile:

Iā€™m trying to achieve this with the recently added FCalculateCustomPhysics delegate, which you can read about .

However I canā€™t get it to work (Iā€™m basically trying to create a new Event Tick BP node only for physics sub-stepping). Any ideas?

Edit: Iā€™m trying to do this with an extension of the actor class - Iā€™m including ā€œPhysicsEngine/BodyInstance.hā€ but I keep getting this error;
Unrecognized type ā€˜FCalculateCustomPhysicsā€™

Edit 2: After some researching - seems like getting a Blueprint to run in the physics thread isnā€™t doable?

Hey.

Newbie to UE4 C++ API.

Could you please elaborate on "YourGameStateā€™, How do i find a reference to it in <<second>> class.

Thank you,

Thnk

To be honest I found this confusing. Often the main problem with code snippets is that they lack context - thereā€™s no indication where things go, what requires declarations and where THEY go. Iā€™m no closer to creating a delegate.

A good solution to this would be to upload a sample project. Looks like a dead thread though sadly.

Yeah, Iā€™ve found this really confusing.

You need to treat people almost like a compiler.

Thereā€™s just too much jumping around and stuff that is disconnected from eachother.

However it is the only tutorial out there for delegates, so Iā€™m very grateful and working through it.

I agree, itĀ“s very confusingā€¦
you should clarify that a variable of type ā€˜FGameStateSigleTODChangedā€™ called 'ā€˜OnMinuteUpdateā€™ is being declared in ā€˜YourGameStateā€™ā€¦

Totally agree with ā€˜Thereā€™s just too much jumping around and stuff that is disconnected from eachother.ā€™

Thanks anyway :slight_smile:

Any other good tutorial? iā€™m noob, and it still confusing me using delegate. :frowning:
Thanks anyway! :slight_smile:

Really nice tuto ! itā€™s really easier than trying with the unreal doc :wink:

thanks manā€¦good to see your next tutsā€¦

What header files are required? Is this ā€œ#include ā€œDelegateCombinations_Variadics.hā€ā€ ?
Where does ā€œDECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParamā€ get defined? Before the class or in the class?

Is there a in .h and .cpp file that show what is going on in context?

Just an fyi, you might want to correct the line,

to

Edit oops, too quick to submit.
Good job, though.

A couple people have commented that this wasnā€™t clear enough.
I found a VERY thorough tutorial on Youtube if anyone is interested:

Interesting thread as a complement : What difference between delegates? - Programming & Scripting - Unreal Engine Forums

Thank You very much for best explanation about Delegates

Thank you! This was really helpful! Awesome explanation! :slight_smile: