Code compiles, but crashes app

So, i have this c++ line of code. It compiles, no errors, but when i run it on a mobile device the app just crashes. Any ideea?
TouchLocationBegin is a FVector2D.



bool Pressed;
UGameplayStatics::GetPlayerController(this, 0)->GetInputTouchState(ETouchIndex::Touch1, TouchLocationBegin.X, TouchLocationBegin.Y, Pressed);


P.S.: This code is not inside the player character, if this matters.

Where are you using this? Are you sure that PlayerController already exists? Have you try protecting your code:



if (UGameplayStatics::GetPlayerController(this, 0))
{
    // use it now
}


I use this inside a function that is executed every tick. I will try your sollution and come back with a reply, thank you.

New code:



AShip::AShip(){
//constructor of the pawn actor
    SteeringWheel = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SteeringWheel"));
    SteeringWheel->OnInputTouchBegin.AddDynamic(this, &AShip::BeginTouchSteeringSheel);
}
void AShip::BeginPlay()
{
    Super::BeginPlay();

    PlayerController = UGameplayStatics::GetPlayerController(this, 0);
    if (!PlayerController) {
        GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("NoController"));
    }
}
void AShip::BeginTouchSteeringSheel(ETouchIndex::Type Touch, UPrimitiveComponent* Component) {
        bool Pressed;
        PlayerController->GetInputTouchState(PlayerRefference->TouchIndex, TouchLocationBegin.X, TouchLocationBegin.Y, Pressed);
}

void AShip::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

        AShip::ControlSteeringWheel();
}


Well, it still crashes. Altough i tested it and the line that crashes the app is the one i showed in the initial post, i added a bit more context, just in case…

P.S.: The debug message does not appear, so il belive the controller is valid.

Is PlayerRefference valid?
Are you running the code directly from VS (F5) and if so are there any error messages? If that line and that function (BeginTouchSteeringSheel) is triggering the crash, what are the values of its parameters? There must be a window in VS with the values of PlayerController, PlayerReference, Pressed, TouchLocationBegin.X and Y when the crash happens.

PlayerRefference was not valid… problem solved. I Thank you for your help, i would not have tought about protecting the code. I am a beginner with c++ :slight_smile:
What happened is that i tryed casting to the player character using GetPlayerController instead of GetPlayerCharacter… i only realised this after seeing that the refference is not valid.