Bird
Raised Fist0
Unityframework~15 mins

Remote procedure calls in Unity - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What attribute do you use in Unity to make a method run on the server when called from a client?
easy
A. [ServerRpc]
B. [ClientRpc]
C. [RunOnServer]
D. [RemoteCall]

Solution

  1. Step 1: Understand the direction of the call

    Client-to-server calls require a special attribute to mark the method that runs on the server.
  2. Step 2: Identify the correct attribute in Unity

    Unity uses [ServerRpc] to mark methods that clients call to run on the server.
  3. Final Answer:

    [ServerRpc] -> Option A
  4. Quick Check:

    Client-to-server calls use [ServerRpc] [OK]
Hint: Client calls server methods with [ServerRpc] attribute [OK]
Common Mistakes:
  • Confusing [ClientRpc] as client-to-server
  • Using non-existent attributes like [RunOnServer]
  • Thinking [RemoteCall] is a valid Unity attribute
2. Which of the following is the correct syntax to declare a server RPC method in Unity?
easy
A. public void MyMethod() { }
B. [ServerRpc] public void MyMethod() { }
C. [ClientRpc] public void MyMethod() { }
D. void [ServerRpc] MyMethod() { }

Solution

  1. Step 1: Recall the attribute placement

    Attributes in C# go before the method declaration.
  2. Step 2: Check the correct attribute and syntax

    The correct syntax is [ServerRpc] public void MyMethod() { }. void [ServerRpc] MyMethod() { } places the attribute incorrectly.
  3. Final Answer:

    [ServerRpc] public void MyMethod() { } -> Option B
  4. Quick Check:

    Attributes precede method declarations [OK]
Hint: Attributes go before method signature in C# [OK]
Common Mistakes:
  • Placing attribute after method name
  • Using [ClientRpc] for server RPC
  • Omitting the attribute entirely
3. Consider this Unity code snippet:
[ServerRpc]
public void SendMessageToClients(string msg) {
    Debug.Log("Server received: " + msg);
    BroadcastMessageClientRpc(msg);
}

[ClientRpc]
void BroadcastMessageClientRpc(string message) {
    Debug.Log("Client received: " + message);
}
What will be printed on the client when SendMessageToClients("Hello") is called from a client?
medium
A. Server received: Hello Client received: Hello
B. Server received: Hello
C. Client received: Hello
D. Nothing is printed on client

Solution

  1. Step 1: Understand the call flow

    The client calls SendMessageToClients which runs on the server due to [ServerRpc]. The server logs "Server received: Hello".
  2. Step 2: Server calls client method

    The server then calls BroadcastMessageClientRpc on all clients, which logs "Client received: Hello" on each client.
  3. Final Answer:

    Client received: Hello -> Option C
  4. Quick Check:

    ClientRpc runs on clients, so clients see "Client received: Hello" [OK]
Hint: Client sees ClientRpc logs, server sees ServerRpc logs [OK]
Common Mistakes:
  • Thinking server logs appear on client
  • Assuming both logs print on client
  • Confusing which method runs where
4. What is wrong with this Unity RPC method?
[ServerRpc]
public void UpdateScoreClientRpc(int score) {
    Debug.Log("Score updated: " + score);
}
medium
A. [ServerRpc] methods must be private
B. Missing return type for RPC method
C. RPC methods cannot have parameters
D. Method name suggests client RPC but uses [ServerRpc] attribute

Solution

  1. Step 1: Analyze method name and attribute

    The method name contains "ClientRpc" but the attribute is [ServerRpc], which is confusing and likely a mistake.
  2. Step 2: Check RPC method rules

    RPC methods can have parameters and must have a return type (void is valid). They can be public. The mismatch between name and attribute is the main issue.
  3. Final Answer:

    Method name suggests client RPC but uses [ServerRpc] attribute -> Option D
  4. Quick Check:

    Method name and attribute must match RPC direction [OK]
Hint: Match method name with RPC attribute to avoid confusion [OK]
Common Mistakes:
  • Ignoring method name and attribute mismatch
  • Thinking parameters are not allowed
  • Assuming RPC methods must be private
5. You want to send a message from the server to all clients except the one who sent the original request. Which approach using Unity RPCs is correct?
hard
A. Use [ClientRpc] with a special NetworkConnection parameter to exclude sender
B. Use [ServerRpc] to send message to clients except sender
C. Use [ClientRpc] and check inside the client to ignore messages from itself
D. Use [ClientRpc] with a parameter to exclude the sender client inside the method

Solution

  1. Step 1: Understand RPC direction

    Server sends messages to clients using [ClientRpc]. To exclude a client, the server must know which client to exclude.
  2. Step 2: Use NetworkConnection parameter

    Unity allows [ClientRpc] methods to take a NetworkConnection parameter to exclude that client from receiving the RPC.
  3. Step 3: Confirm other options

    Use [ClientRpc] with a parameter to exclude the sender client inside the method is incorrect because exclusion logic cannot be done inside the client method. Use [ServerRpc] to send message to clients except sender is wrong direction. Use [ClientRpc] and check inside the client to ignore messages from itself relies on client ignoring messages, which is inefficient.
  4. Final Answer:

    Use [ClientRpc] with a special NetworkConnection parameter to exclude sender -> Option A
  5. Quick Check:

    Exclude sender with NetworkConnection parameter in ClientRpc [OK]
Hint: Exclude sender using NetworkConnection param in ClientRpc [OK]
Common Mistakes:
  • Trying to exclude sender inside client code
  • Using ServerRpc to send to clients
  • Not using NetworkConnection parameter for exclusion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard