In this lesson, you will learn how to create and trigger a single-cast delegate to send a command directly from one object to another.
Understanding Single-Cast Delegates
In Unreal Engine, delegates are a way to "bind" a function to a variable, allowing you to execute that function later without the sender needing to know the specific class of the receiver. A single-cast delegate is the simplest form: it holds a reference to exactly one function. It is perfect for direct, one-to-one communication, such as a "Player" telling a "UI Widget" to update its health bar.
Step 1: Declaring the Delegate
You define the delegate macro in your header file, outside of your class definition. You must specify the return type and the parameters the bound function will accept.
// Declares a delegate named FOnHealthChanged that takes one float parameter
DECLARE_DELEGATE_OneParam(FOnHealthChanged, float);
Step 2: Creating the Delegate Member
Inside your sender class (e.g., UPlayerAttributes), you create an instance of this delegate as a member variable.
public:
FOnHealthChanged OnHealthChanged;
Step 3: Binding and Executing
The receiver (e.g., UPlayerHUD) binds its own function to the delegate. We use BindUObject to safely associate the function with a specific object instance.
// In the receiver class:
MyPlayerAttributes->OnHealthChanged.BindUObject(this, &UPlayerHUD::UpdateBar);
To trigger the communication, the sender simply calls ExecuteIfBound():
// In the sender class:
OnHealthChanged.ExecuteIfBound(NewHealthValue);
Why use this?
By using ExecuteIfBound(), you avoid crashes if nothing is listening to the delegate. If the UPlayerHUD has been destroyed or never bound the function, the delegate remains empty, and the code simply does nothing rather than throwing a null pointer error. This creates a clean, decoupled bridge between your game logic and your user interface.
Key Takeaway: Single-cast delegates allow you to establish a lightweight, direct communication link between two specific object instances while ensuring your code remains safe and decoupled.