0
0
Unityframework~15 mins

Remote procedure calls in Unity - Deep Dive

Choose your learning style9 modes available
Overview - Remote procedure calls
What is it?
Remote Procedure Calls (RPCs) let a program on one computer ask another computer to run a function and send back the result. In Unity, RPCs help different players in a multiplayer game talk to each other by calling functions across the network. This means one player's action can cause something to happen on another player's game. RPCs make multiplayer games feel connected and real-time.
Why it matters
Without RPCs, multiplayer games would struggle to share actions and events between players smoothly. Imagine playing a game where your moves don't show up for others or where you can't affect the game world together. RPCs solve this by making remote communication simple and fast, so players experience a shared world. They are the backbone of real-time interaction in networked games.
Where it fits
Before learning RPCs, you should understand basic Unity scripting and how networking works in Unity, like setting up networked objects. After mastering RPCs, you can explore advanced multiplayer topics like synchronization, lag compensation, and server authority.
Mental Model
Core Idea
RPCs let one computer run a function on another computer as if it were local, making remote communication feel direct and simple.
Think of it like...
It's like calling a friend on the phone and asking them to do something for you, then waiting for their answer, instead of going to their house yourself.
Client A                 Network                 Client B
  ┌─────────┐             ┌─────────┐             ┌─────────┐
  │ Call fn │ ───────────▶│ Message │ ───────────▶│ Run fn  │
  └─────────┘             └─────────┘             └─────────┘
       ▲                                               │
       │                                               ▼
       └───────────────────────── Response ────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a Remote Procedure Call
🤔
Concept: Introduce the basic idea of calling a function on another computer over a network.
A Remote Procedure Call (RPC) is when a program asks another computer to run a function for it. Instead of running the code locally, the request goes over the network. The remote computer runs the function and sends back any results. In Unity, this helps multiplayer games share actions between players.
Result
You understand that RPCs let one device control actions on another device remotely.
Understanding RPCs as remote function calls builds the foundation for how multiplayer games communicate actions.
2
FoundationUnity Networking Basics
🤔
Concept: Learn how Unity connects multiple players and shares game objects over a network.
Unity uses networking systems like Mirror or Netcode for GameObjects to connect players. These systems create copies of game objects on each player’s device and keep them in sync. RPCs are part of this system, letting players send commands or updates to each other.
Result
You see how Unity sets up a shared game world across devices.
Knowing Unity’s networking basics prepares you to understand where RPCs fit in the multiplayer flow.
3
IntermediateHow to Define and Call RPCs in Unity
🤔Before reading on: do you think RPCs are called like normal functions or require special syntax? Commit to your answer.
Concept: Learn the syntax and rules for creating RPC functions in Unity networking frameworks.
In Unity’s Netcode for GameObjects, you mark a method with [ServerRpc] or [ClientRpc] attributes to make it an RPC. ServerRpc means the client calls the server to run the function. ClientRpc means the server calls clients. You call these methods like normal functions, but the system sends the call over the network automatically.
Result
You can write functions that run on other players’ devices by marking them as RPCs.
Understanding the special attributes and call patterns is key to using RPCs correctly in Unity.
4
IntermediateClientRpc vs ServerRpc Explained
🤔Before reading on: do you think ClientRpc and ServerRpc do the same thing or have opposite roles? Commit to your answer.
Concept: Distinguish between the two main types of RPCs in Unity networking and their direction of communication.
ServerRpc functions are called by clients to ask the server to do something, like moving a character. ClientRpc functions are called by the server to tell clients to update something, like showing an explosion. This separation keeps the game state consistent and secure.
Result
You know when to use each RPC type to send messages in the right direction.
Knowing the direction of RPC calls prevents bugs and cheating in multiplayer games.
5
IntermediateParameters and Return Values in RPCs
🤔Before reading on: do you think RPCs can return values directly like normal functions? Commit to your answer.
Concept: Learn how data is sent with RPC calls and the limitations on return values.
RPCs can send parameters like numbers, strings, or custom data to the remote function. However, they cannot return values directly because the call is asynchronous over the network. Instead, you send data back with another RPC or update shared variables.
Result
You understand how to pass data with RPCs and handle responses properly.
Knowing RPCs don’t return values directly helps design communication flows that work over networks.
6
AdvancedHandling Latency and Reliability in RPCs
🤔Before reading on: do you think all RPC calls always arrive instantly and in order? Commit to your answer.
Concept: Explore how network delays and message loss affect RPCs and how Unity handles these issues.
Network messages can be delayed or lost. Unity’s networking systems use reliable or unreliable channels for RPCs. Reliable RPCs retry sending until confirmed but can be slower. Unreliable RPCs are faster but may drop messages. Choosing the right type depends on the game’s needs, like fast updates vs guaranteed actions.
Result
You can design RPC usage that balances speed and reliability for smooth gameplay.
Understanding network behavior behind RPCs helps prevent lag and sync problems in multiplayer games.
7
ExpertSecurity and Authority in RPC Usage
🤔Before reading on: do you think clients can safely call any RPC on the server without checks? Commit to your answer.
Concept: Learn about security risks with RPCs and how to enforce server authority to prevent cheating.
Clients can try to call ServerRpc functions with bad data or cheat commands. Servers must validate all RPC calls and control game state authority. Unity developers often restrict who can call certain RPCs and check inputs carefully. This protects the game from hackers and keeps gameplay fair.
Result
You know how to secure RPCs to maintain a trustworthy multiplayer environment.
Recognizing the security risks of RPCs is critical for building safe and fair multiplayer games.
Under the Hood
When an RPC is called, Unity’s networking system serializes the function name and parameters into a network message. This message is sent over the network to the target machine. The receiving system deserializes the message, finds the matching function, and executes it with the given parameters. This process is asynchronous and managed by the networking framework to handle message ordering and retries.
Why designed this way?
RPCs were designed to make remote communication feel like local function calls, simplifying developer work. Early networking required manual message handling, which was error-prone. By automating serialization and dispatch, RPCs reduce complexity. The separation into ServerRpc and ClientRpc reflects the client-server model common in games, improving security and clarity.
┌─────────────┐       ┌───────────────┐       ┌─────────────┐
│ Caller Code │──────▶│ Serialize RPC │──────▶│ Network Send│
└─────────────┘       └───────────────┘       └─────────────┘
                                                      │
                                                      ▼
┌─────────────┐       ┌───────────────┐       ┌─────────────┐
│ Network Recv│──────▶│ Deserialize RPC│──────▶│ Execute RPC │
└─────────────┘       └───────────────┘       └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think RPCs can return values immediately like normal functions? Commit to yes or no.
Common Belief:RPCs work exactly like normal function calls and return values immediately.
Tap to reveal reality
Reality:RPCs are asynchronous and cannot return values directly; responses must be sent with separate messages.
Why it matters:Expecting immediate return values leads to bugs and confusion in multiplayer code design.
Quick: Do you think clients can call any ServerRpc without restrictions? Commit to yes or no.
Common Belief:Clients can safely call all ServerRpc functions without validation.
Tap to reveal reality
Reality:Servers must validate all client RPC calls to prevent cheating and invalid game states.
Why it matters:Ignoring validation opens security holes and ruins fair gameplay.
Quick: Do you think all RPC messages always arrive in order and without loss? Commit to yes or no.
Common Belief:Network messages for RPCs are always reliable and ordered.
Tap to reveal reality
Reality:Some RPCs use unreliable channels that may drop or reorder messages; developers must handle this.
Why it matters:Assuming perfect delivery causes synchronization bugs and inconsistent game states.
Quick: Do you think RPCs can be used to share large amounts of data efficiently? Commit to yes or no.
Common Belief:RPCs are suitable for sending large data like textures or big files.
Tap to reveal reality
Reality:RPCs are meant for small commands and data; large data should use other methods like streaming or asset bundles.
Why it matters:Misusing RPCs for big data causes lag and network overload.
Expert Zone
1
Some RPC frameworks batch multiple calls into one network packet to reduce overhead, improving performance subtly.
2
The order of RPC execution can differ between clients due to network timing, so game logic must be designed to handle out-of-order events.
3
Using RPCs for state synchronization is less efficient than dedicated syncing methods; experts separate commands (RPCs) from state updates.
When NOT to use
Avoid using RPCs for continuous state synchronization or large data transfers; instead, use state synchronization features or streaming. Also, avoid RPCs in peer-to-peer models without a clear authority to prevent conflicts.
Production Patterns
In production, developers use ServerRpc for client requests like player actions, ClientRpc for server updates like spawning effects, and combine RPCs with state syncing for smooth gameplay. They also implement input validation and rate limiting on RPCs to prevent abuse.
Connections
Client-Server Architecture
RPCs implement communication patterns fundamental to client-server models.
Understanding RPCs deepens comprehension of how clients and servers coordinate tasks and maintain authority.
Asynchronous Programming
RPC calls are asynchronous, similar to promises or async functions in programming.
Knowing asynchronous patterns helps manage RPC timing and responses effectively.
Telephone Communication
RPCs mimic the request-response pattern of phone calls between people.
Recognizing this pattern clarifies how remote calls are initiated, processed, and responded to.
Common Pitfalls
#1Calling RPCs like normal functions expecting immediate results.
Wrong approach:int result = SomeServerRpc(); // expecting immediate return
Correct approach:SomeServerRpc(); // send request // handle response asynchronously via another RPC or event
Root cause:Misunderstanding that RPCs are asynchronous network calls without direct return values.
#2Not validating client input in ServerRpc functions.
Wrong approach:[ServerRpc] void MovePlayer(Vector3 pos) { player.position = pos; } // no checks
Correct approach:[ServerRpc] void MovePlayer(Vector3 pos) { if (IsValid(pos)) player.position = pos; }
Root cause:Assuming client data is always trustworthy leads to security vulnerabilities.
#3Using RPCs to send large data blobs causing lag.
Wrong approach:[ClientRpc] void SendTexture(byte[] data) { /* large data */ }
Correct approach:Use asset bundles or streaming for large data, not RPCs.
Root cause:Misusing RPCs for data transfer instead of commands.
Key Takeaways
Remote Procedure Calls let one device run functions on another over a network, enabling multiplayer interaction.
In Unity, RPCs are marked with special attributes and handle communication between clients and servers asynchronously.
RPCs cannot return values directly and require careful design to handle data flow and timing.
Security is critical: servers must validate all client RPC calls to prevent cheating.
Understanding network reliability and latency helps use RPCs effectively for smooth multiplayer experiences.