Building Escape - Alternative Refactor

During Building Escape - 126 - Which deals with refactoring our Grabber files, we are presented with abstracting LineTraceEnd and it’s components into a new function.

Later on, we see that this causes a conflict because we also need PlayerViewPointLocation. The instructor chooses to make another function that returns this value.

I paused the video early on to see if I could get through the refactor without guidance. This resulted in a different approach to the PlayerViewPointLocation issue.

After doing a bit of Googling, I decided to have GetPlayersReach return an array containing both our LineTraceEnd and our PlayerViewPointLocation. Here is the updated function:

FVector * UGrabber::GetPlayersReachAndLocation() const
{
// Get players viewpoint
	FVector PlayerViewPointLocation;
	FRotator PlayerViewPointRotation;
	// Creating an array so that we can return Reach and Location at once.
	static FVector VectorArray[2];

	GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
		OUT PlayerViewPointLocation,
		OUT PlayerViewPointRotation);

	VectorArray[0] = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;
	VectorArray[1] = PlayerViewPointLocation;

	return VectorArray;
}

When I end up needing either value it looks something like this:

DrawDebugLine(
		GetWorld(),
		//Location
		GetPlayersReachAndLocation()[1],
		//Reach
		GetPlayersReachAndLocation()[0],
		FColor(255, 255, 255),
		false,
		0.f,
		0,
		10.f
	);

Is this bad practice? Am I opening myself up for any performance issues? What’s the best way to answer these questions. I’m a bit weary of going with something just because it works.

1 Like

It works. It is one of the beauties of C++ that arrays are just pointers to blocks of memory. There’s a downside however. It is difficult to be sure that what is returned is actually an array of 2 FVectors and writing code that makes these assumptions isn’t ideal.

Also, a static variable in a function persists between calls which may be unintentional. Returning pointers to variables declared in a function is generally not ideal, which is why a reference or 2 may be used instead.

What might be clearer is to use a structure containing 2 FVectors and return the structure, probably passed in as a reference (I can’t remember exactly how it is done in the course) since they are declared where it is being used. The static is a workaround to persist the returned value as a local variable may not persist

Privacy & Terms