I’ve just spent a couple of hours thinking that GetPawn() was always returning a nullptr and crashing. It’s now working but this has left me confused.
Initially I was having an issue mentioned in another thread here, that GetPawn() crashed the game if I used it as shown in the tutorial. Instead of that, I’m now doing this:
void AMyAIController::BeginPlay()
{
Super::BeginPlay();
if (AIBehavior != nullptr)
{
RunBehaviorTree(AIBehavior);
PlayerPawn = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
AIPawn = GetPawn();
if (AIPawn != nullptr)
{
StartLocation = AIPawn->GetActorLocation();
GetBlackboardComponent()->SetValueAsVector(TEXT("StartLocation"), StartLocation);
}
else
{
UE_LOG(LogTemp, Warning, TEXT("GetPawn failed."));
}
}
}
What I was then seeing in the viewport was that the AI would run up to my player character but then stop and not run back to the start location. Also, I got my “GetPawn failed.” message coming up in the log. I thought that GetPawn() was always returning nothing.
Then I randomly realised that the AI was stopping where it was because my player character was getting in the way of it reaching its endpoint. If I move my player to a different location, the AI completes the first task and then moves onto the second, third, etc as expected. So it’s all working fine.
However, I’m still getting my “GetPawn failed.” message in the log, and I don’t understand why the “else” part is running, because quite clearly the first part of the “if” is ALSO running. Seems really weird and any help would be appreciated.
EDIT:
I don’t know if this is significant, but I have only one AI ShooterCharacter in the level when the game starts, plus the player’s ShooterCharacter that spawns on the PlayerStart. However, when the game starts, I have two BP_AIController assets in the level. I don’t understand why there’s two unless one is attached to the player.
To test this, I tried to change my log message to
UE_LOG(LogTemp, Warning, TEXT("GetPawn failed on %s."), *AIPawn->GetName());
However, changing just this line crashes the game. So I changed the script to this:
if (AIBehavior != nullptr)
{
RunBehaviorTree(AIBehavior);
PlayerPawn = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
AIPawn = GetPawn();
if (AIPawn != nullptr)
{
StartLocation = AIPawn->GetActorLocation();
GetBlackboardComponent()->SetValueAsVector(TEXT("StartLocation"), StartLocation);
UE_LOG(LogTemp, Warning, TEXT("GetPawn succeded on %s."), *AIPawn->GetName());
}
else
{
AIPawn = GetPawn();
if (AIPawn != nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("GetPawn failed on %s."), *AIPawn->GetName());
}
}
}
Now it doesn’t crash, and the log just prints the message “succeded on BP_ShooterCharacter_15”, not the failure message.
My theory is that the player is also creating an AIController asset that has trouble with GetPawn(), but I don’t know how to verify that.