4.17.2 returns null for UGameplayStatics::GetPlayerPawn()

I’m doing something so simple that worked before but not anymore.

I have a C++ Actor Component class called OpenDoor.

AActor *ActorThatOpens;

    PrimaryComponentTick.bCanEverTick = true;

    ActorThatOpens = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
    if (ActorThatOpens == nullptr)
        UE_LOG(LogTemp, Warning, TEXT("Actor is null!"));

When I play, my console output says my pawn is a nullptr even though I am controlling a default pawn when I play on the editor.
How can I fix it? I can’t do anything now because this is such a big feature.

You need to override OnBeginPlay and put your logic there. You’re trying to get the pawn in the constructor which is likely running before the client has actually connected and the player has spawned.

// In your header file.
virtual void OnBeginPlay() override;

// Source
void UOpenDoor::OnBeginPlay()
    ActorThatOpens = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);

Thx man! Your the best! I was going crazy for the past 2 hours trying to figure this out. I swear this worked back then on previous version. Oh well.

P.S: I just got a random editor crash which was pretty much saying I am trying to access a nullptr (read access violation). I opened it again and now its fine…

Yeah you really don’t wanna be doing stuff like that in the Constructor… Constructor is for setup only, not for any game-play logic.