Destroying an Actor using Destroy and a Timer

This recipe will reuse the GameMode from the previous recipe, so you should complete it first.

How to do it...

  1. Make the following changes to the GameMode declaration:
    UPROPERTY()
    AMyFirstActor* SpawnedActor;
    UFUNCTION()
    void DestroyActorFunction();
  2. Add #include "MyFirstActor.h" to the implementation file's includes.
  3. Assign the results of SpawnActor to the new SpawnedActor variable:
    SpawnedActor = GetWorld()->SpawnActor<AMyFirstActor> (AMyFirstActor::StaticClass(), SpawnLocation);
  4. Add the following to the end of the BeginPlay function:
    FTimerHandle Timer;
    GetWorldTimerManager().SetTimer(Timer, this, &AUE4CookbookGameMode::DestroyActorFunction, 10);
  5. Lastly, implement DestroyActorFunction:
    void AUE4CookbookGameMode::DestroyActorFunction() ...

Get Unreal Engine 4 Scripting with C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.