Download

C++ Casting from player controller to player crashes

Hi all,
When I play my game ue4 crashes and says I have an error in my OnPossess function where I’m attempting to get a reference to the player from my controller.

This is the line that gives me the error from the ue4 crash log:
if (AICharacter)

In the function:
*void AAIPatrolController::OnPossess(APawn Pawn)
{
Super::Possess(Pawn);

// Get reference to the character
AAIPatrol* AICharacter = Cast<AAIPatrol>(Pawn);

if (AICharacter)
{
    if (AICharacter->BehaviorTree->BlackboardAsset)
    {
        BlackboardComp->InitializeBlackboard(*(AICharacter->BehaviorTree->BlackboardAsset));
    }

    // Populate patrol point arrray
    UGameplayStatics::GetAllActorsOfClass(GetWorld(), AAIPatrolPoint::StaticClass(), PatrolPoints);

    BehaviorComp->StartTree(*AICharacter->BehaviorTree);
}

}**

Please note that I’ve included the header files for my player.

I think there is probably a simple solution to my problem but I just am not that experienced in ue4 c++ yet

if (AICharacter)
Is a simple null check that you should correctly do in the first place to avoid later crashes.

You might actually be getting a crash on if BehaviorTree is null.
if (AICharacter->BehaviorTree->BlackboardAsset)

This would add a check for that.
if (AICharacter->BehaviorTree && AICharacter->BehaviorTree->BlackboardAsset)

It short circuits the operation so if the first case is false, the entire statement is false so C++ and other languages stop evaluating the rest of the conditions. For some reason Blueprint doesn’t do this.

Thanks for your help, I have just tried this but it still doesn’t work, however I’m getting the crash now from the line were I casted to the character:
AAIPatrol AICharacter = Cast<AAIPatrol>(Pawn);*

When does OnPossess(APawn* Pawn) get called? Could it be that the pawn being passed into this function is null?

I have made sure that my pawn that is being controlled has a reference to my controller in blueprints and I tried a simple null check for the pawn in the beginning of this function just now but it still crashes.

Normally a cast call shouldn’t crash. It should handle NULL and just return NULL if the object was null or can’t be cast.

What does the stack trace and output look like?