C++ OnComponentBeginOverlap not working

Hello hello, I have some problem, try to cast an actor (NPCInteractive) by overlapping it with my box but nothing work, here is my code
CPP file:

#include "WithLoveFromTahitiCharacter.h"
#include "NPCInteractive.h"

AWithLoveFromTahitiCharacter::AWithLoveFromTahitiCharacter()
{
BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollision"));
BoxComponent->InitBoxExtent(FVector(120, 120, 8));
BoxComponent->SetupAttachment(RootComponent);
BoxComponent->OnComponentBeginOverlap.AddDynamic(this, &AWithLoveFromTahitiCharacter::OnOverlapBegin);        // set up a notification for when this component overlaps something
BoxComponent->OnComponentEndOverlap.AddDynamic(this, &AWithLoveFromTahitiCharacter::OnOverlapEnd);
}

void AWithLoveFromTahitiCharacter::OnOverlapBegin(UPrimitiveComponent * OverlapComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{

	ANPCInteractive* NPCInteractive = nullptr;

	if (OtherActor != nullptr)
	{
		NPCInteractive = Cast<ANPCInteractive>(OtherActor);
		if (NPCInteractive != nullptr)
		{
			UE_LOG(LogTemp, Warning, TEXT("OVERLAP"))

		}
	}


}

.h file:

#include "Engine.h"
#include "GameFramework/Character.h"
#include "Components/BoxComponent.h"
#include "WithLoveFromTahitiCharacter.generated.h"

class ANPCInteractive;

UCLASS(config=Game)
class AWithLoveFromTahitiCharacter : public ACharacter
{
	// declare box collision component
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "BoxComponent")
UBoxComponent* BoxComponent;
}

public:

	/** called when something enters the sphere component */
UFUNCTION()
void OnOverlapBegin(class UPrimitiveComponent* OverlapComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);

Thank you guys :slight_smile:

1 Like

Solved by putting this stuff into the BeginPlay, because it is not working into the constructor.

void AWithLoveFromTahitiCharacter::BeginPlay()
{
	Super::BeginPlay();

	BoxComponent->OnComponentBeginOverlap.AddDynamic(this, &AWithLoveFromTahitiCharacter::OnOverlapBegin); 
	BoxComponent->OnComponentEndOverlap.AddDynamic(this, &AWithLoveFromTahitiCharacter::OnOverlapEnd);
}
2 Likes

Thank you for this; you sir are a star!