In this lesson, you will learn how to trigger visual or audio events across all connected clients simultaneously using the ClientRpc attribute.
The Role of ClientRpc
While NetworkVariable is perfect for keeping data like player health or object transforms in sync, it isn't ideal for "one-off" events like playing a particle effect, triggering a explosion sound, or showing a UI pop-up. For these transient actions, we use ClientRpc (Remote Procedure Call).
When the server wants to tell every client to perform an action—such as playing an animation when a boss is defeated—it invokes a ClientRpc method. The server sends a message to all connected clients, and each client executes that method locally. Because the logic runs on every client, every player sees the effect happen at the same time.
Implementation Example
To implement this, ensure your script inherits from NetworkBehaviour. Use the [ClientRpc] attribute above the method declaration.
public class EffectManager : NetworkBehaviour
{
// Called by the server when an explosion occurs
public void TriggerExplosion(Vector3 position)
{
// Execute the visual effect on all clients
ClientRpcExplosion(position);
}
[ClientRpc]
private void ClientRpcExplosion(Vector3 position)
{
// This code runs on the Server AND every Client
Instantiate(explosionPrefab, position, Quaternion.identity);
audioSource.PlayOneShot(explosionClip);
}
}
Important Considerations
- Execution Scope: By default, a
ClientRpcexecutes on all connected clients. If you need to target a specific client, you can useClientRpcParams. - Latency: Remember that
ClientRpcmessages are subject to network jitter. If you need an event to be perfectly frame-accurate across all players, you may need to implement additional delay compensation or rely onNetworkVariabletimestamps, but for general visual feedback,ClientRpcis the industry-standard approach. - Reliability: You can configure the
RpcDeliveryparameter if you need to ensure the message is delivered reliably, though for non-critical visual effects, the default unreliable delivery is often preferred to save bandwidth.
Key Takeaway: Use ClientRpc to broadcast transient, one-time events from the server to all clients, ensuring that every player experiences the same visual and audio feedback simultaneously.