Caching PlayerPawn reference

Are there any downsides to caching the PlayerPawn reference in BeginPlay() as opposed to searching for the reference every frame?

in ShooterAIController.h

private:
	UPROPERTY(VisibleAnywhere)
	APawn* PlayerPawn;

in ShooterAIController.cpp

void AShooterAIController::BeginPlay()
{
	Super::BeginPlay();
	PlayerPawn = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
	SetFocus(PlayerPawn);
	
}

void AShooterAIController::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	if(LineOfSightTo(PlayerPawn))
	{
		SetFocus(PlayerPawn);
		MoveToActor(PlayerPawn, 2);
	} else
	{
		ClearFocus(EAIFocusPriority::Gameplay);
		StopMovement();
	}
	
}

The only thing that comes to mind offhand, make sure it’s not null. My first thoughts were actually how would it be handled during death/respawn. In the Controller I could see that being an issue, but you could figure out some ways around that.

Yeah, I left out the null check for now…
Actually, the very next lesson, we comment all that code out and head for Behavior Tree Town, so… I guess my question’s moot.

1 Like

I’m pretty sure this would come up again in a BT task. To me it would make sense to store it, with that said, in the grand scheme of things, I doubt it would be the cause of any performance hit.

It may also depend on how may times. I would expect a performance hit if hundreds or thousands of scripts are running it.

I would prefer to get in the habit of caching the reference instead of calling each frame.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms