Course contentsShow
← Unreal Engine Game Development
Lesson 697 of 88010. Networking and ReplicationFree lesson

Managing Variable Replication with RepNotify

Learners will use RepNotify functions to execute specific logic on clients immediately after a replicated variable receives a new value from the server.

In this lesson, you will learn how to use RepNotify to execute custom logic on clients the exact moment a replicated variable is updated by the server.

The Problem with Simple Replication

When you replicate a variable, the server updates its value and pushes that change to all connected clients. However, the client simply receives the new value; it doesn't automatically "know" that a change occurred. If you need to trigger a visual effect, update a UI element, or play a sound in response to that data change, standard replication isn't enough. This is where ReplicationNotify (RepNotify) bridges the gap.

How RepNotify Works

When you set a variable's Replication property to RepNotify, Unreal Engine automatically generates a special function—usually named OnRep_VariableName—on the actor.

Whenever the client receives a new value for this variable from the server, the engine calls this function. This is the perfect place to put logic that depends on the state of that variable.

Consider a simple health bar system:

// In your Header
UPROPERTY(ReplicatedUsing=OnRep_Health)
float Health;

UFUNCTION()
void OnRep_Health();

// In your Implementation
void AMyCharacter::OnRep_Health()
{
    // This runs on the client every time 'Health' is updated by the server
    UpdateHealthBarUI(Health);
    
    if (Health <= 0)
    {
        PlayDeathAnimation();
    }
}

Critical Implementation Details

  1. Separation of Concerns: The OnRep function is only called on clients. The server does not automatically trigger its own OnRep function when it changes the variable value. If you need the server to execute the same logic, you must call the OnRep function manually within the server-side code where you modify the variable.
  2. Deterministic State: Because OnRep functions run whenever the variable is synchronized, they ensure that your client-side representations (like UI, sounds, or cosmetic effects) remain perfectly synchronized with the authoritative state held on the server.

Key Takeaway: Use RepNotify to transform passive data replication into active client-side responses, ensuring your visuals and logic update instantly whenever the server pushes new state information.