Mini-Tutorial: Using UPawnSensingComponent in C++

UPDATE 4.22!!!

hI! I would like to add my contribution here!! Here’s how I did my enemy character with a pawn sensing

in my enemycharacter.h :


//the BlueprintCallable is crucial!! -- well for my case, yes.
    UFUNCTION(BlueprintCallable)
        void OnSeePawn(APawn* SeenPawn);



enemycharacter.cpp:


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

    if (GEngine)
        GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Orange, TEXT("EnemyCharacter"));

    FScriptDelegate fScriptDelegate;
    fScriptDelegate.BindUFunction(this, "OnSeePawn");
    pawnSensor->OnSeePawn.AddUnique(fScriptDelegate);
}

Since adddynamic was removed, I have been using FScriptDelegate to bind the function. It acts like a glue between the event and your code, it’s the same method as dynamic event.


void AEnemyCharacter::OnSeePawn(APawn* OtherPawn)
{
    if (GEngine)
        GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Blue, TEXT("PawnSensingfunction"));

    auto playerPawn = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);

    if (OtherPawn == playerPawn)
    {
        FString message = TEXT("Saw Actor ") + OtherPawn->GetName();
        GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, message);
    }
}

Enjoy!!

1 Like