Spawning and Destroying an Actor

In this How-To guide, you will create your own Actor to spawn, and aActor Spawner which will spawn your Actor at the click of a button.

Choose your operating system:

Windows

macOS

Linux

Choose your implementation method:

Blueprints

C++

Oftentimes in video games, players are kept engaged by attaining new items or weapons for their character, and sometimes new enemies may even appear for them to defeat.

In your game, you may wish to dynamically add items or enemies to your Level during gameplay, this is called spawning.

In this How-To guide, you will create an Actor class that will be spawned from an Actor spawner at the press of a button. Then, you will create the logic to destroy the spawned Actors at the press of a different button.

image alt text

Creating the Actor to Spawn

In this section, you will create an Actor that contains a Sphere Component, a Static Mesh Component, and a Particle System Component.

  1. Begin by creating a new Third Person Blueprint games project, with Starter Content set to enabled . Name your project SpawnDestroy .

    image_1.png

  2. From the Content Browser , select the Add/Import button and create a new Blueprint Actor class named Bp_ActorToSpawn .

    image_2.png

  3. In the Class Defaults , navigate to the Components tab and select Add Component . Then, search for and select the Sphere Component , and drag it over the Scene Component to make it the new Root Component .

    image_3.png

  4. In the Details panel of the Sphere Component navigate to the Shape category and change the Sphere Radius value to 16.0 .

    image_4.png

  5. Navigate to the Physics category and check the box next to the Simulate Physics variable.

    image_5.png

  6. Navigate to the Components tab and select Add Component , then search for and select the Static Mesh Component .

    image_6.png

  7. In the Details panel, locate the Static Mesh category and select the dropdown arrow next to the Static Mesh variable. Then, search for and select the Shape_Sphere Static Mesh asset.

    image_7.png

  8. Navigate to the Transform category and from the Scale variable, change the X, Y, and Z values to 0 .25 , 0 .25 , 0 .25. Then from the Location variable, change Z value to -12.0 .

    image_8.png

  9. Navigate to the Components tab and select Add Component . Search for and select the Particle System Component .

    image_9.png

  10. Navigate to the Details panel and from the Particles category, select the dropdown arrow next to the Template variable, then search for and select P_Fire .

    image_10.png

  11. Compile & save your Blueprint.

    image_11.png

Finished Blueprint

image_12.png

Creating the Actor Spawner

Now that you have created an Actor to spawn, you will create an Actor spawner which contains a custom function to spawn your new Bp_ActorSpawn Blueprint.

  1. From the Content Browser , select the Add/Import button and create a new Blueprint Actor class named Bp_ActorSpawner .

    image_13.png

  2. From the Class Defaults , navigate to the Components tab and select Add Component . Then, search for and select the Box Component and rename it to SpawnVolume .

    image_14.png

  3. Right-click the Event Graph , from the Actions context menu, search for and select Add Custom Event , then name it SpawnActor .

    image_15.png

  4. Drag off of the Spawn Actor Custom Event execution pin and from the Executable actions dropdown menu, search for and select Spawn Actor From Class .

    image_16.png

  5. From the SpawnActor node Class pin, select the BP_ActorToSpawn class.

    image_17.png

  6. Click and drag off of the Spawn Transform pin from the Spawn Actor from Class node, then from the Actions dropdown menu search for and select Get Actor Transform .

    image_18.png

  7. Compile & save your Blueprint.

    image_19.png

Finished Blueprint

image_20.png

Setting Up Additional Character Action Commands

Now that you have created your two Actor classes, Bp_ActorToSpawn and Bp_ActorSpawner, you will now be tasked with setting up the Third Person Character with the functionality to call the Actor spawner's Spawn Actor function.

  1. Navigate to Edit > Project Settings > Engine > Input , then from the Bindings > Action Mappings category, click the + button to add two additional mappings named SpawnActors and DestroyActors .

    image_21.png

  2. Set the SpawnActors action key mapping to numeric 1 key, and the DestroyActors Action key mapping to the numeric 2 key.

    image_22.png

  3. From the Content Browser , navigate to your Third Person Character Blueprint and double-click to open its class defaults, then right-click the Event Graph. From the All Actions for this Blueprint context menu, search for and select the SpawnActors input action.

    image_23.png

  4. Drag off the Pressed execution pin and from the Executable actions dropdown menu search for and select the Get Actor Of Class node. Then, click the dropdown arrow for the Actor Class and select Bp Actor Spawner .

    image_24.png

  5. Drag off the Return value pin of the Get Actor of Class node. In the Actions menu search for and select the call function Spawn Actor , then connect the execution pin from the Get Actor Of Class node to the execution pin of the Spawn Actor node.

    image_25.png

  6. Right-click the Event Graph and from the context menu, search for and select the DestroyActors Input Action Event.

    image_26.png

  7. Drag off the Pressed execution pin and from the Executable actions dropdown menu search for and select the Get All Actors Of Class node. Then, click the dropdown arrow for the Actor Class and select Bp Actor to Spawn .

    image_27.png

  8. Drag off the Out Actors Return value pin and from the dropdown menu search for and select the For Each Loop With Break node.

    image_28.png

  9. Drag off the Array Element pin and from the Actions menu, search for and select the Destroy Actor function, then connect the output execution pin from the Get All Actors of Class node into the Execution Pin of the For Each Loop with Break node .

  10. Next, connect the Loop Body execution pin from the For Each Loop with Break node into the Destroy Actor input execution pin.

    image_29.png

  11. Compile & save .

    image_30.png

Finished Blueprint

image_31.png

Setting Up the Scene

Now that you have finished creating the functionality necessary for the Player Character to call the Bp_Spawner's SpawnActor function, you will need to choose the location of the Bp_Spawner in the Level.

  1. From the Content Browser , drag an instance of your Bp_ActorSpawner into the Level.

    image_32.png

  2. Select PIE (Play-In Editor) to test your Bp_ActorSpawner.

End Result

When testing in the editor, if you press the 1 key, then the Actor Spawner class will spawn its Actor into the Level. If you decide to press the 2 key, then all ActorsToSpawn within the Level will be destroyed.

image_33.gif

Creating the Actor to Spawn

  1. Begin by creating a new Third Person C++ games project with Starter Content enabled. Name your project SpawnDestroy .

    image_34.png

  2. From the C++ class wizard create a new Actor class named ActorToSpawn .

    image_35.png

  3. In the Class defaults of ActorToSpawn.h implement the following.

    protected:
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite)
        class USphereComponent* SphereComp;
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite)
        UStaticMeshComponent* StaticMeshComp;
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite)
        class UParticleSystemComponent* ParticleComp;
  4. Navigate to ActorToSpawn.cpp and declare the following class libraries.

    #include "Components/SphereComponent.h"
    #include "Particles/ParticleSystemComponent.h"
  5. Within the AActorToSpawn::AActorToSpawn constructor, implement the following code.

    AActorToSpawn::AActorToSpawn()
    {
        // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
        PrimaryActorTick.bCanEverTick = true;
    
        //Creating our Default Components
        SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));
        StaticMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
        ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleComp"));
    
        //Attaching the Components and setting physics
        SphereComp->SetupAttachment(RootComponent);
        SphereComp->SetSimulatePhysics(true);
        SphereComp->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
    
        StaticMeshComp->AttachToComponent(SphereComp,FAttachmentTransformRules::KeepRelativeTransform);
        ParticleComp->AttachToComponent(StaticMeshComp,FAttachmentTransformRules::KeepRelativeTransform);
    
        //Setting the Sphere radius to be of a smaller size in line with the Static Mesh.
        SphereComp->SetSphereRadius(16.0f);
    
        //Setting the Static Mesh Scale and Location to fit the radius of the Sphere.
        StaticMeshComp->SetRelativeLocation(FVector(0.0, 0.0, -12.0f));
        StaticMeshComp->SetRelativeScale3D(FVector(0.25, 0.25, 0.25));
    
        //Using Constructor Helpers to set our Static Mesh Comp with a Sphere Shape.
        static ConstructorHelpers::FObjectFinder<UStaticMesh>SphereMeshAsset(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere'"));
        StaticMeshComp->SetStaticMesh(SphereMeshAsset.Object);
    
        //Using Constructor Helpers to set our Particle Comp with our Fire Particle Comp.
        static ConstructorHelpers::FObjectFinder<UParticleSystem>ParticleCompAsset(TEXT("ParticleSystem'/Game/StarterContent/Particles/P_Fire.P_Fire'"));
        ParticleComp->SetTemplate(ParticleCompAsset.Object);
    }
  6. Compile your code.

  7. In the editor, navigate to the C++ classes folder , and right-click your ActorToSpawn . From the context menu, select Create Blueprint class based on ActorToSpawn .

    image_36.png

    Your completed Bp_ActorToSpawn will look similar to the image below.

    image_37.png

Finished Code

ActorToSpawn.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ActorToSpawn.generated.h"

UCLASS()
class SPAWNDESTROYCPP_API AActorToSpawn : public AActor
{
    GENERATED_BODY()

public: 
    // Sets default values for this actor's properties
    AActorToSpawn();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    class USphereComponent* SphereComp;

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    UStaticMeshComponent* StaticMeshComp;

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    class UParticleSystemComponent* ParticleComp;

public: 
    // Called every frame
    virtual void Tick(float DeltaTime) override;
};

ActorToSpawn.cpp

#include "ActorToSpawn.h"
#include "Components/SphereComponent.h"
#include "Particles/ParticleSystemComponent.h"

// Sets default values
AActorToSpawn::AActorToSpawn()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    //Creating our Default Components
    SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));
    StaticMeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
    ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("ParticleComp"));

    //Attaching the Components and setting physics
    SphereComp->SetupAttachment(RootComponent);
    SphereComp->SetSimulatePhysics(true);

    SphereComp->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
    StaticMeshComp->AttachToComponent(SphereComp,FAttachmentTransformRules::KeepRelativeTransform);
    ParticleComp->AttachToComponent(StaticMeshComp,FAttachmentTransformRules::KeepRelativeTransform);

    //Setting the Sphere radius to be of a smaller size in line with the Static Mesh.
    SphereComp->SetSphereRadius(16.0f);

    //Setting the Static Mesh Scale and Location to fit the radius of the Sphere.
    StaticMeshComp->SetRelativeLocation(FVector(0.0, 0.0, -12.0f));
    StaticMeshComp->SetRelativeScale3D(FVector(0.25, 0.25, 0.25));
}

// Called when the game starts or when spawned
void AActorToSpawn::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void AActorToSpawn::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

Creating the Actor Spawner

Now that you have created an Actor to Spawn, you will create an Actor spawner which uses a custom function to spawn your new Actor.

  1. From the C++ class wizard create a new Actor class named ActorSpawner .

    image_38.png

  2. In the class defaults of your ActorSpawner.h implement the following code

    public:
    
        UFUNCTION()
        void SpawnActor();
    
    protected:
        UPROPERTY(EditAnywhere,BlueprintReadWrite)
        class UBoxComponent* SpawnVolume;
  3. Navigate to the ActorSpawner.cpp and include the following class libraries

    #include "Components/BoxComponent.h"
    #include "ActorToSpawn.h"
  4. Inside the AActorSpawner::AActorSpawner constructor implement the following code.

    AActorSpawner::AActorSpawner()
    {
        RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("DefaultSceneRoot"));
        SpawnVolume = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnVolume"));
        SpawnVolume->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
    }
  5. Implement the following code for the AActorSpawner::SpawnActor class method.

    void AActorSpawner::SpawnActor()
    {
        FVector SpawnLocation = GetActorLocation();
        FRotator SpawnRotation = GetActorRotation();
    
            GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);
    }
  6. Compile your code.

  7. From the Content Browser , navigate to your C++ classes folder , and right-click your ActorSpawner class, from the C++ Class Actions context menu, select Create Blueprint class based on ActorSpawner named Bp_ActorSpawner .

    image_39.png

    Your completed Blueprint will look like the image below.

    image_40.png

Finished Code

ActorSpawner.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ActorSpawner.generated.h"

UCLASS()
class SPAWNDESTROYCPP_API AActorSpawner : public AActor
{
    GENERATED_BODY()

public: 
    // Sets default values for this actor's properties
    AActorSpawner();

    UFUNCTION()
    void SpawnActor();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

    UPROPERTY(EditAnywhere,BlueprintReadWrite)
    class UBoxComponent* SpawnVolume;

public: 
    // Called every frame
    virtual void Tick(float DeltaTime) override;
};

ActorSpawner.cpp

#include "ActorSpawner.h"
#include "Components/BoxComponent.h"
#include "ActorToSpawn.h"

// Sets default values
AActorSpawner::AActorSpawner()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("DefaultSceneRoot"));
    SpawnVolume = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnVolume"));

    SpawnVolume->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}

// Called when the game starts or when spawned
void AActorSpawner::BeginPlay()
{
    Super::BeginPlay();
}

void AActorSpawner::SpawnActor()
{
    FVector SpawnLocation = GetActorLocation();
    FRotator SpawnRotation = GetActorRotation();
    GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);
}

// Called every frame
void AActorSpawner::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
}

Setting Up Additional Character Action Commands

With both your Actor and Actor spawner classes set up, you will now set up the Third Person Character with the functionality to call the Actor spawner's Spawn Actor function. You will also need to map your input keys mappings for the Player Character to provide your player the ability to call the Actor spawner's Spawn Actor function.

  1. Navigate to Edit > Project Settings > Engine > Input , then from the Bindings > Action mappings category, click the + button to add two additional mappings named SpawnActors and DestroyActors.

    image_41.png

  2. Set the SpawnActors Action key mapping to numeric 1 key, and the DestroyActors Action key mapping to the numeric 2 key.

    image_42.png

  3. Open your ThirdPersonCharacter.h file and declare the following class declarations.

    protected:
        void SpawnActors();
        void DestroyActors();
  4. Navigate to your ThirdPersonCharacter.cpp and include the following class libraries.

    #include "Kismet/GameplayStatics.h"
    #include "ActorSpawner.h"
    #include "ActorToSpawn.h"

    GameplayStatics contains useful gameplay utility functions that can be called from both Blueprint and C++. For additional information see the following API documentation for GameplayStatics .

  5. Implement the following class implementation for your ASpawnDestroyCppCharacter::SpawnActors and ASpawnDestroyCppCharacter::DestroyActors methods.

    void ASpawnDestroyCppCharacter::SpawnActors()
    {
        //Find the Actor Spawner in the world, and invoke it's Spawn Actor function
        AActor* ActorSpawnerTofind = UGameplayStatics::GetActorOfClass(GetWorld(),AActorSpawner::StaticClass());
    
        AActorSpawner* ActorSpawnerReference = Cast<AActorSpawner>(ActorSpawnerTofind);
        if (ActorSpawnerReference)
        {
            ActorSpawnerReference->SpawnActor();
        }
    }
    
    void ASpawnDestroyCppCharacter::DestroyActors()
    {
        //Get every Actor to Spawn in the world and invoke Destroy Actor
        TArray<AActor*> FoundActors;
        UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActorToSpawn::StaticClass(), FoundActors);
        for (AActor* ActorFound :FoundActors)
        {
            ActorFound->Destroy();
        }
    }
  6. Navigate to your ASpawnDestroyCppCharacter::SetupPlayerInputComponent method and add the following code.

    void ASpawnDestroyCppCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
    {
        PlayerInputComponent->BindAction("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors);
        PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors);
    }

Finished Code

SpawnDestroyCppCharacter.h

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "SpawnDestroyCppCharacter.generated.h"

UCLASS(config=Game)
class ASpawnDestroyCppCharacter : public ACharacter
{
    GENERATED_BODY()

    /** Camera boom positioning the camera behind the character */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
    class USpringArmComponent* CameraBoom;

    /** Follow camera */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
    class UCameraComponent* FollowCamera;

public:
    ASpawnDestroyCppCharacter();

    /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
    float BaseTurnRate;

    /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
    float BaseLookUpRate;

protected:
    /*Calls Actor Spawner in Level to Spawn their Actor to Spawn*/
    void SpawnActors();

    /*Gets all ActorToSpawn Actors and call their Destroy function */
    void DestroyActors();

    /** Resets HMD orientation in VR. */
    void OnResetVR();

    /** Called for forwards/backward input */
    void MoveForward(float Value);

    /** Called for side to side input */
    void MoveRight(float Value);

    /** 
     * Called via input to turn at a given rate. 
     * @param Rate  This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
     */
    void TurnAtRate(float Rate);

    /**
     * Called via input to turn look up/down at a given rate. 
     * @param Rate  This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
     */
    void LookUpAtRate(float Rate);

    /** Handler for when a touch input begins. */
    void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location);

    /** Handler for when a touch input stops. */
    void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location);

protected:

    // APawn interface
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
    // End of APawn interface

public:

    /** Returns CameraBoom subobject **/
    FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }

    /** Returns FollowCamera subobject **/
    FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; }
};

SpawnDestroyCppCharacter.cpp

#include "SpawnDestroyCppCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
#include "Kismet/GameplayStatics.h"
#include "ActorSpawner.h"
#include "ActorToSpawn.h"
//////////////////////////////////////////////////////////////////////////
// ASpawnDestroyCppCharacter

ASpawnDestroyCppCharacter::ASpawnDestroyCppCharacter()
{
    // Set size for collision capsule
    GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

    // set our turn rates for input
    BaseTurnRate = 45.f;
    BaseLookUpRate = 45.f;

    // Don't rotate when the controller rotates. Let that just affect the camera.
    bUseControllerRotationPitch = false;
    bUseControllerRotationYaw = false;
    bUseControllerRotationRoll = false;

    // Configure character movement
    GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...   
    GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
    GetCharacterMovement()->JumpZVelocity = 600.f;
    GetCharacterMovement()->AirControl = 0.2f;

    // Create a camera boom (pulls in towards the player if there is a collision)
    CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
    CameraBoom->SetupAttachment(RootComponent);
    CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character   
    CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

    // Create a follow camera
    FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
    FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
    FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

    // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) 
    // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}

//////////////////////////////////////////////////////////////////////////
// Input

void ASpawnDestroyCppCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
    // Set up gameplay key bindings
    check(PlayerInputComponent);
    PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
    PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);

    PlayerInputComponent->BindAction("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors);
    PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors);
    PlayerInputComponent->BindAxis("MoveForward", this, &ASpawnDestroyCppCharacter::MoveForward);
    PlayerInputComponent->BindAxis("MoveRight", this, &ASpawnDestroyCppCharacter::MoveRight);

    // We have 2 versions of the rotation bindings to handle different kinds of devices differently
    // "turn" handles devices that provide an absolute delta, such as a mouse.
    // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
    PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
    PlayerInputComponent->BindAxis("TurnRate", this, &ASpawnDestroyCppCharacter::TurnAtRate);
    PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
    PlayerInputComponent->BindAxis("LookUpRate", this, &ASpawnDestroyCppCharacter::LookUpAtRate);

    // handle touch devices
    PlayerInputComponent->BindTouch(IE_Pressed, this, &ASpawnDestroyCppCharacter::TouchStarted);
    PlayerInputComponent->BindTouch(IE_Released, this, &ASpawnDestroyCppCharacter::TouchStopped);

    // VR headset functionality
    PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ASpawnDestroyCppCharacter::OnResetVR);
}

void ASpawnDestroyCppCharacter::SpawnActors()
{

    //Find the Actor Spawner in the Level, and invoke it's Spawn Actor function
    AActor* ActorSpawnerTofind = UGameplayStatics::GetActorOfClass(GetWorld(),AActorSpawner::StaticClass());
    AActorSpawner* ActorSpawnerReference = Cast<AActorSpawner>(ActorSpawnerTofind);

    if (ActorSpawnerReference)
    {
        ActorSpawnerReference->SpawnActor();
    }
}

void ASpawnDestroyCppCharacter::DestroyActors()
{
    TArray<AActor*> FoundActors;
    UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActorToSpawn::StaticClass(), FoundActors);
    for (AActor* ActorFound :FoundActors)
    {
        ActorFound->Destroy();
    }
}

void ASpawnDestroyCppCharacter::OnResetVR()
{
    // If SpawnDestroyCpp is added to a project via 'Add Feature' in the Unreal Editor the dependency on HeadMountedDisplay in SpawnDestroyCpp.Build.cs is not automatically propagated
    // and a linker error will result.
    // You will need to either:
    //      Add "HeadMountedDisplay" to [YourProject].Build.cs PublicDependencyModuleNames in order to build successfully (appropriate if supporting VR).
    // or:
    //      Comment or delete the call to ResetOrientationAndPosition below (appropriate if not supporting VR)
    UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}

void ASpawnDestroyCppCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
        Jump();
}

void ASpawnDestroyCppCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
        StopJumping();
}

void ASpawnDestroyCppCharacter::TurnAtRate(float Rate)
{
    // calculate delta for this frame from the rate information
    AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}

void ASpawnDestroyCppCharacter::LookUpAtRate(float Rate)
{
    // calculate delta for this frame from the rate information
    AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}

void ASpawnDestroyCppCharacter::MoveForward(float Value)
{
    if ((Controller != nullptr) && (Value != 0.0f))
    {
        // find out which way is forward
        const FRotator Rotation = Controller->GetControlRotation();
        const FRotator YawRotation(0, Rotation.Yaw, 0);

        // get forward vector
        const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
        AddMovementInput(Direction, Value);
    }
}

void ASpawnDestroyCppCharacter::MoveRight(float Value)
{
    if ( (Controller != nullptr) && (Value != 0.0f) )
    {
        // find out which way is right
        const FRotator Rotation = Controller->GetControlRotation();
        const FRotator YawRotation(0, Rotation.Yaw, 0);

        // get right vector 
        const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);

        // add movement in that direction
        AddMovementInput(Direction, Value);
    }
}

Setting Up the Scene

Now that you have finished creating the functionality necessary for the Player Character to call the Bp_Spawner's SpawnActor function, you will need to set up the location of the Bp_Spawner in the Level.

  1. From the Content Browser , click and drag an instance of your Bp_ Spawner into the Level.

    image_43.png

  2. Select PIE (Play-In Editor) to test your spawner.

End Result

When testing in the Editor, if you press the 1 key, then the Actor Spawner class will spawn its Actor to spawn into the Level. If you decide to press the 2 key, then all ActorsToSpawn within the Level will be destroyed.

image_44.gif

Help shape the future of Unreal Engine documentation! Tell us how we're doing so we can serve you better.
Take our survey
Dismiss