Hello guys.
I’ve been working on my project for some time now, and I’ve run into a problem that I think is so critical in nature that I’m surprised it works this way.
I’m talking about PlayerController initialization happening after BeginPlay() of objects on the map, but let’s take it one step at a time.
To start with, I have my own MyPlayerController class, in MyGameMode I set it as PlayerControllerClass.
In the editor I create a blueprint of successors from MyPlayerController and MyGameMode and for BP_MyGameMode PlayerControllerClass is BP_MyPlayerController.
This is the most standard behavior and there are no problems here.
I don’t know how architecturally correct this is, but almost every game class, be it MyPlayerHUD (AHUD) or MyUnit (ACharacter) uses MyPlayerController. I pull it up in the BeginPlay() of a particular class. it looks like this:
void ARGResourceBase::BeginPlay()
{
Super::BeginPlay();
OnClicked.AddDynamic(this, &ARGResourceBase::HandleOnClicked);
PlayerController = Cast<ARGPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
if (!PlayerController)
{
UE_LOG(LogRGResourceBase, Warning, TEXT("[BeginPlay] PlayerController is nullptr."))
return;
}
PlayerPawn = Cast<ARGPlayerPawn>(PlayerController->GetPawn());
if (!PlayerPawn)
{
UE_LOG(LogRGResourceBase, Warning, TEXT("[BeginPlay] PlayerPawn is nullptr."))
return;
}
}
And everything seemed fine, in the editor I spent about a month with this architectural solution gradually working on the project and yesterday I decided to make a build and then everything fell apart.
Log.WriteException: ERROR: Client exited with error code: -1073741819 (accessing nullptr)
Also in all classes in which I pull up MyPlayerController the log that MyPlayerController is nullptr is written out.
Experimentally, I realized that this line:
PlayerController = Cast(UGameplayStatics::GetPlayerController(GetWorld(), 0));
Assigns my PlayerController to nullptr because of a Cast issue, it fails
Although if I check the class I get, I get this:
BP_RGPlayerController
Also based on the UE forum I learned that the initialization order in the editor and build is different, but how can this be related and how to fix it.
It doesn’t seem to me that this is some very specific problem and someone has already encountered this, I am very much asking for your help and would be very grateful.
If anyone is interested in the problem in more detail, message me in the DM and I will add you to the repo to investigate the situation further.