Are there any events that are called AFTER Begin Play

Un tizio tizio
Tue, 10 Sep 2024 09:31:39 +0000
Programming & Scripting

Hi.
I’ve already posted two posts regarding a specific problem that I’ve been facing for days without any solution:

I don’t get how Delegates / Events works on Unreal Engine

UE5 C++ event doesn’t fire

But now after days of debugging the whole code I think I’ve found where the problem is.

So basically I have an HealthComponent (C++) that fires a Delegate everytime the Health is set: OnSetHealth. The listener of this delegate is in my WBP_HUD, that is a Widget Blueprint, because I want to update the Health Bar every time the event is fired.

Ideally I would broadcast the delegate in Begin Play like this:

void UHealthComponent::BeginPlay()
{
	Super::BeginPlay();

	SetHealth(MaxHealth);
}
void UHealthComponent::SetHealth(const int Value)
{
	CurrentHealth = FMath::Clamp(Value, 0, MaxHealth);
	OnSetHealth.Broadcast(MaxHealth, CurrentHealth);
}

while this is the logic inside the WBP_HUD:

The problem is that Begin Play is always called BEFORE any WBP event like On Initialized or Event Constructor, because they get called AFTER the UI has been displayed, which means it doesn’t bind the event in time.

One work around that I’ve found was broadcasting the delegate in the Tick event just for the first frame, but this obviously seems pretty Spagetti code:

void UHealthComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
	if (bFirstTick)
	{
		SetHealth(MaxHealth);
		bFirstTick = false;
	}
}

So for this reason I’m asking if there’s any event that are called after Begin Play

7 posts - 2 participants