How do i get a reference to a BP playercontroller in my code?

Hello,

I am quite new at all this, so please be kind if i write stupid/wrong things.

I created a playercontroller class MyPC in my code.

From that, i created a BP class BP_MyPC in the editor.

Now back in my code i would like to get a reference to my ingame player controller so i can use methods from MyPC class.

I read a way to do this is the following:

playerController = GEngine->GetFirstLocalPlayerController(GWorld);

The problem is what type should i use for the variable playerController ?

I tried to cast:

MyPC *playerController = Cast<MyPC>( GEngine->GetFirstLocalPlayerController(GWorld) );

This compiles well but crashes at runtime, i guess because i am casting a child (BP_MyPC) to a parent (MyPC), which memory probably doesn’t like.

The c++ code doesn’t know about the blueprint class.

I tried to play around with the generatedclass taken from the following code in the gamemode:

static ConstructorHelpers::FObjectFinder<UBlueprint> PlayerControlerObjet(TEXT("Blueprint'/Game/player/BP_MyPC.BP_MyPC'"));
PlayerControllerClass = (UClass*)PlayerControlerObjet.Object->GeneratedClass;

But i went nowhere.

So how can i do this ?

Can i use PlayerControllerClass in some template or something ?

Thanks

Cedric

If it crash when you cast it means it’s not object of a class you casting in to, generally you should check if object is class you expect to be before casting to avoid clashes, also hold casted object pointer. Also most UE4 classes got refrence to eachother so first check if you can access PlayerController from inside the class (without accessing world context) before using GetFirstLocalPlayerController.

As for using blueprint, i think safer will be if you make blueprint from GameMode extended from your C++ GameMode and set default PlayerController there.

Thanks for the tips, i’ll check all that…

And i didn’t think about creating the BP class directly in the code, i associated BP with editor in my head, i’ll try that for sure, very good idea.

Thank you very much