Update players UI when a replicated variable is changed

Hey guys, I’m starting to practice multiplayer programming in Unreal and I’m working on a task which involves having an actor with a replicated variable called ‘Counter’. When players click on it with the left mouse button, ‘Counter’ increases by one, and if they click with the right mouse button, it decreases. If shift key is being pressed when players click on the actor, ‘Counter’ will increase or decrease by 10 units. ‘Counter’ is correctly replicated in real-time across all clients. Here are the RPCs that I’m using to replicate Counter through everyone.

// Server call
void ATaskThreeActor::SR_UpdateCounter_Implementation(bool bAdding, ATechnicalTestPlayerController* PC)
{
	if(PC)
	{
		if(HasAuthority())
		{
			MC_UpdateCounter(bAdding, PC);
		} 
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("%hs: PlayerController is NULL"), __FUNCTION__);
	}
}

// Multicast call
void ATaskThreeActor::MC_UpdateCounter_Implementation(bool bAdding, ATechnicalTestPlayerController* PC)
{
	UpdateCounter(bAdding, PC);
}

void ATaskThreeActor::UpdateCounter(bool bAdding, ATechnicalTestPlayerController* PC)
{
	if(PC)
	{
		if(bAdding)
		{
			PC->GetPlayerState<ATechnicalTestPlayerState>()->bShiftPressed ? Counter += 10 : Counter++;
		}
		else
		{
			PC->GetPlayerState<ATechnicalTestPlayerState>()->bShiftPressed ? Counter -=10 : Counter--;
			Counter = FMath::Clamp(Counter, 0, Counter); // Forbid < 0 values
		}
		OnCounterUpdated.Broadcast();
	}
}

As you can see in the code above, I have a delegate that is called anytime ‘Counter’ variable is updated. The issue arises when I try to create a Widget on players that reflects the value of ‘Counter’ in real-time for all clients; I can’t seem to figure out the correct way to do it. I’ve tried everything (or at least everything I could think of) to achieve this: storing a reference of the actor in the widget and assigning the delegate to a widget function, doing the same in the player and having the player responsible for calling the widget afterward… The closest I’ve come is updating the UI for the player who is clicking on the actor, but I’m really stack with this issue. Is there something that I’m missing?

I managed to solve this issue. It turns out that when calling MC_UpdateCounter(bool bAdding, ATechnicalTestPlayerController* PC), the clients lose the reference to the PC variable, causing the code not to execute correctly.

It seems to be a common occurrence when making multicast calls, so as a piece of advice, it’s preferable not to pass the PlayerController in multicast functions. I solved it by calling the Character instead of the PlayerController, fixing the issue properly.

1 Like

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