Write Get Controller, Player State and Player Name that I have in BP into C++

Hello UE Community!

I want to have these stuff (Set Player Name Box) in Blueprint translated into C++. I have a multiplayer project and if I write these in BP it won’t actually get the ‘PlayerName’ of the specific character that I have chosen but your own character. In this project all characters exist on the Server.

I have very few knowledge in C++ syntax so hopefully someone could be so kind to help me write this in C++

My sincerest gratitude!

As you can see, I’m tryna get the PlayerController, PlayerState and PlayerName, and then set the PlayerName as a new variable in the CharacterBP…

I’ll start with the delay on begin play for that we need to set a timer with we can do like so

void APaper2DLightsCharacter::BeginPlay() <-- replace APaper2DLightsCharacter with your class
{
  Super::BeginPlay();

  FTimerHandle DelayHandel;

  GetWorldTimerManager().SetTimer(DelayHandel, this, &APaper2DLightsCharacter::OnDelayEnd, 1.0f);  <-- replace APaper2DLightsCharacter with your class
}

    #include "TimerManager.h" <--- remember to add this include

So 1 second after begin play the OnDelayEnd function is called we can now get the player controller which in multiplayer is best to do by index remember tho it starts at 0 so player one’s index will be 0

    #include "GameFramework/PlayerController.h" <-- add the includes
    #include "GameFramework/PlayerState.h"
    #include "kismet/GameplayStatics.h"
void APaper2DLightsCharacter::OnDelayEnd()
{
  APlayerController* PController = UGameplayStatics::GetPlayerController(this, 0); // put player index here

  if (PController)
  {
    MyPlayerName = PController->PlayerState->GetPlayerName();
  }
}

then here is my .h file

  UPROPERTY(BlueprintReadOnly, Category = "Player Info") // this makes it so you call this string in blueprint
  FString MyPlayerName;

  void OnDelayEnd();

hope this puts you on the right track

Wow thank you so so much! The code is very nice and clean and thanks for commenting it! I’m starting to learn more about the syntax, used to be really confused about " :: ", " → " and various operator signs. I feel a lot clearer since you showed what these signs will mean in BP. Thanks again I’m gonna try this out right now.

ya no problem if you wanna learn more C++ syntax I would recommend talking this course on Udemy https://www.udemy.com/course/unrealcourse/ it’s really helpful it’s how I learned C++

bought the tutorial and the code is working great, thanks again!