"Get Player Character" like blueprint?

Hey,

how can i get my Player Character like i do in blueprints? I’m totaly new to C++ and worked through some basic tutorials. I set up a Variable

UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = References)
ASurvivalCharacter* MyCharacter;

in the Headerfile of another class. This is working and a can see the Variable in the blueprint, but how can i get the character in the .cpp file? In blueprints there is a function called “Get Player Character” which can be cast to the specific character class. But i can’t find that in c++.

And this is a multiplayer game!

Ok, after googling half of the WWW i found out how to get the character

for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
       MyCharacter = Cast<ASurvivalCharacter>(*ActorItr);
}

MyCharacter is the one i created in the header.

It also works with ->Role to check if its the server or the client. Took me some time to test, but changing a variable on both depending on server or client showed me that it is working (i hope x))

UGameplayStatics::GetPlayerCharacter(GetWorld(),0);

This one is cheaper than iterating over all actors.

10 Likes