Adding an overlap sphere to a NPC

Hello!
I’m following a tutorial on beginning to use UE4 with C++. It’s very good, although it seems to have used atleast UE4 4.4.

I’m trying to add an overlap sphere to a NPC in such a way that if my character collides the sphere, it will trigger something on the NPC’s side.

For now, I’ve got this in “MuhNPC.h” under SetupPlayerInputComponent :

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Collision)
		USphereComponent* ProxSphere;

	UFUNCTION(BlueprintNativeEvent, category = "Collision")
		void Prox(AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);

And the author proposed to put this in “MuhNPC.cpp”.

//To be able to collide with the overlap sphere and talk with the npc
AMuhNPC::AMuhNPC(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP)
{
	ProxSphere = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("Proximity Sphere"));

	ProxSphere->AttachTo(RootComponent);
	ProxSphere->SetSphereRadius(32.f);
	//This will activate ANPC::Prox() when the sphere overlaps another actor
	ProxSphere->OnComponentBeginOverlap.AddDynamic(this, &AMuhNPC::Prox);
	NpcMessage = "Hi, I'm Gytha";
}

It seems that the method he uses is outdated. I’ve searched a bit, and it seems that this PCIP thing isn’t used anymore. How could I do this in another way?

Sure, I wrote this myself a little while ago. It should work for you. PCIP was replaced with ObjectInitializer. :slight_smile:

/// .h file

    UPROPERTY(VisibleAnywhere, Category = "Switch Components")
    	class UBoxComponent * Box1;
    
    	UFUNCTION()
    		void OnOverlap(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
    
    	UFUNCTION()
    		void OnEndOverlap(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);


///////////////
.cpp file. This goes into the constructor.

    Box1 = ObjectInitializer.CreateDefaultSubobject<UBoxComponent>(this, TEXT("BoxStuff"));
    	Box1->bGenerateOverlapEvents = true;
    	Box1->SetRelativeScale3D(FVector(1.5, 1.5, 3.0));
    	Box1->AttachTo(CapsuleComponent);
    	Box1->OnComponentBeginOverlap.AddDynamic(this, &ABasicAICharacter::OnOverlap);
    	Box1->OnComponentEndOverlap.AddDynamic(this, &ABasicAICharacter::OnEndOverlap);

Thanks, that did it!

Awesome! Please be sure to mark the answer as correct so others may find it useful. Have a great day!

Hi, great, I am able to succeed doing it, but with a BoxSphere it does not occur.