How can I replicate a variable from client to server?

There are several great guides on replication out there:

Official documentation – Networking and Multiplayer | Unreal Engine Documentation
Wiki – A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums

And many youtubes.

In short, you can do that from actors that are ‘owned’ by the client, which is usually Player Controller or Player Character. Other non-player Pawns are owned by the server, however whatever happens to those would be either controlled on the server already, or caused by the player. If player causes this variable change, then you could implement this as Player’s Server function.

So PlayerCharacter would have function declared as Server function in PlayerCharacter.h:



	UFUNCTION(Server, Reliable, WithValidation)
		void ServerChangeVar(AActor* TargetedActor, float NewValue);
	virtual bool ServerChangeVar_Validate(AActor* TargetedActor, float NewValue) { return true; };
	virtual void ServerChangeVar_Implementation(AActor* TargetedActor, float NewValue);


And in PlayerCharacter.cpp implement just the _Implementation version:



void APlayerCharacter::ServerChangeVar_Implementation(AActor* TargetedActor, float NewValue)
{
    TargetedActor->ReplicatedVariable = NewValue;
}


To trigger all this, just call ServerChangeVar(ActorToChange, NewValue) where appropriate.

This will make a call on the server, which will change value of that actor’s variable to new value, and replication will then propagate the change to the same actor of all connected clients.

Note that my _Validation function always return true; in real cases, from time to time it may be required to prevent cheats by actually validating this variable change. Returning ‘false’ will disconnect the client that attempted to make the call.

Good luck!

2 Likes