When to pass in parameters and when not to

Hi,

I’m hoping to understand the behavior of my code a bit better. When I was initially doing the first challenge in this lesson (refactor code by placing OpenDoor code into its own function), I initially approached it by defining it with 3 parameters: CurrentYaw, TargetYaw, and DeltaTime.

void UOpenDoor::OpenDoor(float CurrentYaw, float TargetYaw, float DeltaTime)
{
	CurrentYaw = FMath::Lerp(CurrentYaw, TargetYaw, DeltaTime * 1.f);
	FRotator DoorRotation = GetOwner()->GetActorRotation();
	DoorRotation.Yaw = CurrentYaw;
	GetOwner()->SetActorRotation(DoorRotation);
}

Calling this function in the TickComponent function, I noticed that this code does not open the door as I was expecting. I can see by using UE_LOG’s that the CurrentYaw isn’t updating every frame, and appears to be getting overwritten instead. I know that by defining the function without the CurrentYaw and TargetYaw parameters, the values do update each frame and the door opens.

The part that confuses me is that I would expect my original function to run each frame, accept the CurrentYaw, TargetYaw, and DeltaTime arguments, update the CurrentYaw value (via the Lerp function), then use the updated value in the next iteration. I’m sure it’s a simple misunderstanding, but if anyone would be able to explain the difference in how values are passed around in the OpenDoor(float DeltaTime) case and the OpenDoor(float CurrentYaw, float TargetYaw, float DeltaTime) case I would find it very helpful!

You are using “pass by value” for your parameters. This means they are copies of the arguments. You would need to pass by reference in order to modify CurrentYaw. However since they are member variables it doesn’t really make sense to have them as parameters.

That’s a great explanation, thank you! I knew that the values weren’t being updated, and it’s very useful to know why. I can see why I wouldn’t want to have member variables as parameters since they would already be in scope of the function. To help myself understand the concepts better I was able to get the function to work by passing the values by reference when I defined the function:

void UOpenDoor::OpenDoor(float &CurrentYaw, float &TargetYaw, float DeltaTime)

As you said, once the values are referenced the door opens. Thanks!

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

Privacy & Terms