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()
    {
      if (SpawnedActor != nullptr)
      {
        SpawnedActor->Destroy();
      }
    }
  6. Load the level you created in the previous recipe, which had the game mode set to your custom class.
  7. Play your level, and use the Outliner to verify that your SpawnedActor gets deleted after 10 seconds.

How it works...

  • We declare a 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();
  • 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 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);
  • The DestroyActorFunction checks if we have a valid reference to a spawned Actor:
    void AUE4CookbookGameMode::DestroyActorFunction()
    {
      if (SpawnedActor != nullptr)
    }
  • If we do, it calls Destroy on the instance, so it will be destroyed, and eventually, garbage collected:
    SpawnedActor->Destroy();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.169.139