In this lesson, you will learn how to trigger specific, one-off events across a network using Remote Procedure Calls (RPCs) to ensure all connected clients witness actions like visual effects or global sound triggers simultaneously.
The Concept of RPCs
While NetworkVariable is perfect for keeping states synchronized (like a player's health or position), it isn't meant for "events." If you want a player to fire a weapon and have everyone else hear a "bang" or see a muzzle flash, you don’t need to track that state indefinitely. Instead, you need a way to tell other clients: "Execute this specific function right now." That is the role of an RPC.
An RPC allows a client or the server to invoke a method on other machines. Because networks have latency, these calls are treated as messages sent over the wire, instructing the receiving clients to run a local function as soon as the packet arrives.
Implementation Example
To define an RPC in a script inheriting from NetworkBehaviour, you use specific attributes (depending on your networking framework, like Netcode for GameObjects). Here is how you might broadcast a global sound effect:
[ServerRpc]
public void RequestPlaySoundServerRpc()
{
// The server receives the request, then tells everyone else to play it
PlaySoundClientRpc();
}
[ClientRpc]
private void PlaySoundClientRpc()
{
// This executes on every client connected to the session
audioSource.Play();
}
When to Use RPCs
Use RPCs sparingly. Because they are individual messages, sending them too frequently—such as inside an Update() loop—will flood your network bandwidth and cause lag or dropped packets. They are best reserved for discrete "fire and forget" actions:
- Playing particle effects (e.g., an explosion).
- Triggering UI announcements (e.g., "Player has scored!").
- Playing non-looping audio clips.
By routing these through an RPC, you ensure the action remains localized to the players currently in the scene, keeping the network traffic lean while maintaining a synchronized experience for everyone.
Key Takeaway: Use RPCs to trigger transient, one-time network events that don't require persistent state tracking, keeping your synchronization logic efficient and clean.