Why call GetFirstPlayerController each tick?

First post (sorry)…doing this after the kids have gone to sleep so limited time for the social stuff :slight_smile:
Really enjoying the course so far!

Wondering why we don’t store the result of GetWorld()->GetFirstPlayerController() somewhere (either in a FController*(?) variable in BeginPlay(), or as a Private variable in the header?)

Then we would just be calling MyPlayerControler->GetPlayerViewPoint each tick, instead of doing the extra search each tick, since, the player controller (I assume) will not change after BeginPlay?

If I had more time to experiment, I would have tried this myself last night , but it was getting late, and it takes 4 or 5 minutes to compile each time on my machine (rather envious of your 4 second compile time Ben!)


I am referring to this code snippet in Graber.cpp

void UGrabber::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) 31 { 32 .. .. 37 ***GetWorld()->GetFirstPlayerController()***->GetPlayerViewPoint( 38 OUT PlayerViewPointLocation, 39 OUT PlayerViewPointRotation 40 ); 41

PS. I was really confused as to how we could call .ToString(), since I thought that was a method for another type (that we used in PositionReport.cpp for eg) , but …I see now that it is Also a method of FVector and FRotator Types!..yay… leraning learning

For what its worth, I tried with a Private AController* and only setting it the once (in BeginPlay), and it works ok.
I can only assume that not doing the Top down search for FirstPlayerController each tick is better?..now I just reference the PlayerController location already stored each tick.

Probably redundant later on?..not sure…glad it works though, means I understood it!


// Called when the game starts
void UGrabber::BeginPlay()
	UE_LOG(LogTemp, Warning, TEXT("Grabber Running"));
--->	PlayerController = GetWorld()->GetFirstPlayerController();

// Called every frame
void UGrabber::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
	Super::TickComponent( DeltaTime, TickType, ThisTickFunction );

	FVector PlayerViewPointLocation;
	FRotator PlayerViewPointRotation;

--->	PlayerController->GetPlayerViewPoint(
		OUT PlayerViewPointLocation,
		OUT PlayerViewPointRotation


	AController* PlayerController;

Well we could do that but it adds complexity and 1 pointer lookup doesn’t exactly cost very much. If we were doing a find by type that would indeed be more expensive and worth optimizing.

Great, thanks Sam!

Craig in first spot you not show the variable return as a pointer.

38 OUT *PlayerViewPointLocation,
39 OUT *PlayerViewPointRotation

this way you return the value from memory because the GetPlayerViewPoint() return nothing

Privacy & Terms