This recipe will reuse the GameMode
from the previous recipe, so you should complete it first.
GameMode
declaration:UPROPERTY() AMyFirstActor* SpawnedActor; UFUNCTION() void DestroyActorFunction();
#include "MyFirstActor.h"
to the implementation file's includes.SpawnActor
to the new SpawnedActor
variable:SpawnedActor = GetWorld()->SpawnActor<AMyFirstActor> (AMyFirstActor::StaticClass(), SpawnLocation);
BeginPlay
function:FTimerHandle Timer; GetWorldTimerManager().SetTimer(Timer, this, &AUE4CookbookGameMode::DestroyActorFunction, 10);
DestroyActorFunction
:void AUE4CookbookGameMode::DestroyActorFunction() { if (SpawnedActor != nullptr) { SpawnedActor->Destroy(); } }
SpawnedActor
gets deleted after 10 seconds.UPROPERTY
to store our spawned Actor
instance, and a custom function to call so that we can call Destroy()
on a timer:UPROPERTY() AMyFirstActor* SpawnedActor; UFUNCTION() void DestroyActorFunction();
BeginPlay
, we assign the spawned Actor
to our new UPROPERTY
:SpawnedActor = GetWorld()->SpawnActor<AMyFirstActor> (AMyFirstActor::StaticClass(), SpawnLocation);
TimerHandle
object, and pass it to GetWorldTimerManager::SetTimer
. SetTimer
calls DestroyActorFunction
on the object 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, hence, we declare it in advance so that we can pass it into the function properly:FTimerHandle Timer; GetWorldTimerManager().SetTimer(Timer, this, &AUE4CookbookGameMode::DestroyActorFunction, 10);
DestroyActorFunction
checks if we have a valid reference to a spawned Actor
:void AUE4CookbookGameMode::DestroyActorFunction() { if (SpawnedActor != nullptr) }
Destroy
on the instance, so it will be destroyed, and eventually, garbage collected:SpawnedActor->Destroy();
18.222.169.139