Detect change in a variable

Hello, I want to know whats the best way to detect if a variable has changed or not. And how does the Unreal Engine server Replication handle it?
When a server variable is changed, it is replicated to client but how to detect that change efficiently?

The easiest way I can of doing is store the variable in another clone variable and check if it is changed ever “Tick” and then update the clone variable. Pretty easy but i have around 40-80 variables so i don’t want to do it each tick. Are there any other efficient ways?

“best” is kind of difficult to tell.

But to avoid ticking, an Event Dispatcher (BP) or a Multicast Delegate Broadcast (C++) every time you “set” a new value to the variable “could” do the trick.

Hope this helps. :smiley:

I have never used delegates yet no experience with them. Any hints how to make it work?

I am thinking of setting a wrapper on my structure which needs to be called to set the value. The problem is, there are places in the code where i have set value by reference. I need to change them.

I would create a setter function and only change the variable through this function (make the variable itself private), then handle the notification within the setter. I could imagine that the Replication code creates something like that behind the scenes, but I don’t know.

[Edit: Sorry just noticed that this is what you are already planning. Yeah you will have to change the code using references I guess, just come up with a good system for your specific use case.]

When you’re working with replicated variables UE has a mechanism exactly to tell you when a remote client receives a change in value from the server! You should mark your variable ReplicatedUsing=MyFunction where MyFunction is a UFUNCTION. For example in your header file:



	UFUNCTION()
	void OnRep_MyReplicatedVariable();
	UPROPERTY(ReplicatedUsing = OnRep_MyReplicatedVariable)
	int32 MyReplicatedVariable;


Whenever the value of MyReplicatedVariable is changed server-side (or by its net owner? I’m not sure about this) and this value ‘arrives’ at the client, then the client automatically executes the specified function. In Blueprint this is known as RepNotify. The server though does not automatically execute the function, so usually what is done is calling the function manually after changing the variable server-side so that it is executed on both server and client: server-side due to the manual call and client-side because the value changed.

Server-side example code:



// Change will result in OnRep_MyReplicatedVariable() call client-side
MyReplicatedVariable++;

// Manually call the handler server-side
OnRep_MyReplicatedVariable();