Why does this Pointer return nullptr in a Function but in a begin play function works fine

APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);

Can someone explain to me why this pointer returns the correct playercontroller in the Begin Play Function but when I use the same code in a custom function I call from another class it returns nullptr? Here is the code I am using. When I put this code into the Begin Play Function it returns not null, when I use it in a custom function that I call from another class It returns null and I have no idea why.

    APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);

    if (OurPlayerController)
    {
        GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("NOT null"));
    }
    if (OurPlayerController == nullptr)
    {
        GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("null"));
    }

Hi, would you be able to provide more context in how you are using it in this custom function from that other class you mention? Depending on when this custom function is called, it could be that the player controller is not valid yet; but this is just a guess. Additionally, the first parameter of UGameplayStatics::GetPlayerController is the World Context Object so maybe you need to use GetWorld().