Code destroys actor immediately instead of on triggerbox overlap.

Hi guys

I know that I am overlooking something simple with my code.

Essentially I have set up a C++ Actor that destroys itself as soon as I step into its triggerbox. However upon pressing play, it immediately destroys itself. I suspect I have to tell it to only destroy when the player enters the triggerbox but I am not sure how to do this. Here is my code:

Ground.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include “GameFramework/Actor.h”
#include “Ground.generated.h”

UCLASS()
class CPP_IME_API AGround : public AActor
{
GENERATED_BODY()

public:
AGround();

//This is for the triggerBox
UPROPERTY(EditAnywhere)
	UShapeComponent* triggerBox;

//Triggerbox overlap.
UFUNCTION()
	void TriggerEnter(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);

//For testing purposes this must be kept
FVector PlayerStartingLocation = FVector(-640.0f, 980.0f, 180.0f);

};

====================

Ground.cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include “CPP_IME.h”
#include “Ground.h”

// Sets default values
AGround::AGround()
{

// Create and position a mesh component so we can see where our sphere is
UStaticMeshComponent* GroundVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
RootComponent = GroundVisual;
static ConstructorHelpers::FObjectFinder<UStaticMesh> GroundVisualAsset(TEXT("/Game/Ground/Ground"));
if (GroundVisualAsset.Succeeded())
{
	GroundVisual->SetStaticMesh(GroundVisualAsset.Object);
	GroundVisual->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
	GroundVisual->SetWorldScale3D(FVector(1.0f));
}


//Triggerbox properties.
triggerBox = CreateDefaultSubobject<UBoxComponent>(TEXT("Root"));
triggerBox->OnComponentBeginOverlap.AddDynamic(this, &AGround::TriggerEnter);
triggerBox->SetRelativeScale3D(FVector(15.0f, 15.0f, 5.0f));

triggerBox->AttachTo(RootComponent);

}

void AGround::TriggerEnter(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
//Here is where the issue is. Upon play it immediately destroys
//the actor. I need it to destroy the actor when I step in the triggerbox,
//not right at the beginning.
Destroy();
}

===

Any thoughts? And thank you in advance.

This code looks okay. Maybe log OtherActor->GetName() to see if there isn’t another unexpected object triggering the overlap.

Safer to auto player = Cast<AMyPlayer>(OtherActor) and test if a valid actor is triggering the Destroy().

You have it just blindly calling Destroy(). You should be checking to make sure OtherActor->IsA(APlayerPawnClass::StaticClass()) otherwise anything, BSP/terrain ground will trigger the event during spawn I believe.



if(OtherActor->IsA(YourPawnClass::StaticClass())
{
 Destroy();
}