Skip to main content

OnComponentBeginOverlap

Official Documentation: docs.unrealengine.com.

Description

Event called when something starts to overlaps this component, for example a player walking into a trigger.

For events when objects have a blocking collision, for example a player hitting a wall, see 'Hit' events.

@note Both this component and the other one must have GetGenerateOverlapEvents() set to true to generate overlap events.

@note When receiving an overlap from another object's movement, the directions of 'Hit.Normal' and 'Hit.ImpactNormal' will be adjusted to indicate force from the other object against this object.

Idea

Useful to call some functionality if you enter a certain Area, like a Cutscene or to check if you are in range to Interact with Some Actor.

SomeActor.h
#include "Components/SphereComponent.h" // add this to your includes
//#include "Components/BoxComponent.h" // or any Collision Volume you want

protected:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Collision")
UShapeComponent* CollisionVolume; // Give it a fitting Name

public:
// Name this function however you want
UFUNCTION()
void OnXXXOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult);

Next, lets implement the Overlap in our .cpp file.

SomeActor.cpp
// Input
AActor::AActor()
{
// Construct the Collision Volume and Attach it to a specific component or to the RootComponent
CollisionVolume = CreateDefaultSubobject<USphereComponent>(TEXT("CollisionVolume"));
CollisionVolume->SetupAttachment(RootComponent); // or attach to SkeletalMeshComponent
// Create Delegate and reference the function we created earlier, to call when overlapped
CollisionVolume->OnComponentBeginOverlap.AddDynamic(this, &AActor::OnXXXOverlap);
}

void AActor::OnXXXOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult)
{
// Check if OtherActor is not null && check for a specific Class - this is optional
if (OtherActor && OtherActor->IsA(AAnotherActor::StaticClass()))
{
// do something here...
// here is an example:
AAnotherActor* AnotherActor = Cast<AAnotherActor>(OtherActor); // Cast to the Actor that got got

if (AnotherActor)
{
// do something with the actor e.g. apply damage
AnotherActor->Health -= 10.f;
}
}
}
Important

Dont forget to enable Overlap in the Actors Details Panel under Collision and set it to OverlapAllDynamics.

This was an example on how to use OnComponentBeginOverlap in Unreal Engine C++.