We declare a UPROPERTY to store our spawned Actor instance, and a custom function so that we can call Destroy() on a timer:
UPROPERTY() AMyFirstActor* SpawnedActor;
UFUNCTION() void DestroyActorFunction();
In BeginPlay, we assign the spawned Actor to our new UPROPERTY:
SpawnedActor = GetWorld()->SpawnActor<AMyFirstActor>
(AMyFirstActor::StaticClass(), SpawnLocation);
We then declare a TimerHandle object and pass it to GetWorldTimerManager::SetTimer. SetTimer calls DestroyActorFunction on the object that was pointed to by this pointer after 10 seconds. SetTimer returns an object – a handle – to allow us to cancel the timer if necessary. The SetTimer function takes the TimerHandle object in as a reference parameter, and so we declare it in advance so that we can pass it into the function properly, even if we aren't going to be using it again:
FTimerHandle Timer; GetWorldTimerManager().SetTimer(Timer, this,
&AUE4CookbookGameMode::DestroyActorFunction, 10);
DestroyActorFunction checks whether we have a valid reference to a spawned Actor:
void AUE4CookbookGameMode::DestroyActorFunction() { if (SpawnedActor != nullptr)
{
// Then we know that SpawnedActor is valid
} }
If we do, it calls Destroy on the instance so it will be destroyed and, eventually, garbage-collected:
SpawnedActor->Destroy();