OnDestroyed Dynamic function not being called

I have a timer actor that I intend to place in some levels of my game that will force a game over if the player doesn’t complete their objectives in time. This works if they run out of time, but I’ve realized that the timer keeps going even if they successfully move on to the next level, which then leads to a crash as the timer code tries to reference a world that no longer exists. To remedy this, I tried to add an OnDestroyed callback that just clears the timer by the custom handle I passed it when BeginPlay was called, but when I try to breakpoint that callback I see that it doesn’t get called when the levels swap. So either the actor isn’t getting destroyed when the level ends, or something else is preventing the OnDestroyed callback is firing that I am unaware of. What’s going on???

GameOverCountdown.cpp

// Called when the game starts or when spawned
void AGameOverCountdown::BeginPlay()
{
	Super::BeginPlay();
	
	// verify valid time has been set before setting timer
	if (CountdownTime > 0) {
		// start timer that'll trigger Overlord's game over when 0
		GetWorldTimerManager().SetTimer(
			GameOverHandle,
			FTimerDelegate::CreateLambda(
				[&] {
					AOverlordGameModeBase* OverloardGM = Cast<AOverlordGameModeBase>(GetWorld()->GetAuthGameMode()); // <-- crashes here
					// make sure were in the right game mode
					if (OverloardGM) {
						OverloardGM->GameOver();
					}
				}),
			CountdownTime,
					false);
	}
	// clear the timer when this is destroyed (when the level is ended)
	this->OnDestroyed.AddDynamic(this, &AGameOverCountdown::ClearTimer);
}

void AGameOverCountdown::ClearTimer(AActor* Timer)
{
	GetWorldTimerManager().ClearTimer(GameOverHandle); // <-- never called
}

Believe EndPlay should be used for level transitions. Source.

Tested and EndPlay does execute when unloading level.

// h
UFUNCTION()
	void ClearTimer(AActor* Actor, EEndPlayReason::Type EndPlayReason);

// cpp
this->OnEndPlay.AddDynamic(this, &AGameOverCountdown::ClearTimer);

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.