How can I replicate a variable from client to server?

I have a few variables concerning input on the client. If I use variable replication the server doesn’t receive the client’s changes. How do I replicate input from the client to the 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!

Never trust to the client, client in the hands of the enemy:)

Lol, I have to trust it’s input though.
OR I could create a game where the clients can’t do anything.
Hmm, that IS innovative.

Okay, I created two tests. I made replicated variables for the client controlled character and it’s controller. Neither one of them replicated to the server. I know I can use the UFUNCTION(server) etc stuff, but that is only for functions. While it works it seems more like a work around than a proper solution. I wanted to know the proper way to do this.

Idk, maybe server functions is the correct solution. If this is the case please let me know.

Variables are only ever replicated from Server to Client, never the other way around. The only way to go from Client to Server, is via replicated functions, (and hence the option to validate this input before trusting it)

Thank you. I guess I was doing it properly all along. :slight_smile: