Access Player from c++

Hi.
I am trying to get the reference to the player controller object (MyCharacter_C) from a custom made c++ class. How do I go about it?

P.S. I am accessing other objects using TActorIterator<AActor> ActorItr(GetWorld()), but, I can`t figure out a way to access the player controller.

Thanks for the help in advance.

APlayerControlleris a subclass of AActor. You should be able to iterate using TActorIterator<AActor> ActorItr(GetWorld()), then useCast<APlayerController> to test for your player controller. If it’s non NULL, you’ve found it.

You might be able to do something like this:



for (FConstPlayerControllerIterator Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator)
{
     APlayerController* PlayerController = *Iterator;
     if (PlayerController)
     {
         ...........
         .........
     }
}


Jon

1 Like

Thanks. That solved it. The working code:

for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{

	APlayerController* PC = Cast&lt;APlayerController&gt;(*ActorItr);
	if (PC)
	{
		
		GlobalPositionOfSoldier = PC-&gt;GetPawn()-&gt;GetActorLocation();
		GlobalRotOfSoldier = PC-&gt;GetPawn()-&gt;GetActorRotation();
	}
	
}

Because this is a top google search result, note that the above code for using GetPlayerControllerIterator does not seem to work as of 4.22. I have to use the following to get a playerController reference.



for (FConstPlayerControllerIterator iter = GetWorld()->GetPlayerControllerIterator(); iter; ++iter) {
    APlayerController *playerController = iter->Get();
    //...
}


4 Likes

No need for any iteration, you can just use:


UGameplayStatics::GetPlayerController(this, 0) //for singleplayer

3 Likes