0
0
Unityframework~5 mins

Remote procedure calls in Unity

Choose your learning style9 modes available
Introduction

Remote procedure calls let different computers or devices talk and work together by asking each other to run specific tasks.

When you want players in a multiplayer game to see the same actions happen at the same time.
When you need to send a message from one device to another to update game data.
When you want to trigger an event on another player's game, like opening a door or playing a sound.
When you want to keep all players' game states in sync during online play.
Syntax
Unity
using UnityEngine;
using Unity.Netcode;

public class ExampleRPC : NetworkBehaviour
{
    [ServerRpc]
    public void MyServerRpc()
    {
        // Code runs on the server
    }

    [ClientRpc]
    public void MyClientRpc()
    {
        // Code runs on clients
    }
}

[ServerRpc] marks a method that clients call to run code on the server.

[ClientRpc] marks a method that the server calls to run code on all clients.

Examples
This example shows a method that a player calls to tell the server they jumped.
Unity
using UnityEngine;
using Unity.Netcode;

public class PlayerActions : NetworkBehaviour
{
    [ServerRpc]
    public void JumpServerRpc()
    {
        Debug.Log("Player jumped on server");
    }
}
This example shows the server telling all players to play a sound.
Unity
using UnityEngine;
using Unity.Netcode;

public class GameEvents : NetworkBehaviour
{
    [ClientRpc]
    public void PlaySoundClientRpc()
    {
        Debug.Log("Play sound on all clients");
    }
}
Sample Program

This program lets the player press space to jump. The jump is sent to the server with a ServerRpc. The server logs the jump and tells all clients to play a jump sound with a ClientRpc.

Unity
using UnityEngine;
using Unity.Netcode;

public class RPCExample : NetworkBehaviour
{
    void Update()
    {
        if (IsOwner && Input.GetKeyDown(KeyCode.Space))
        {
            JumpServerRpc();
        }
    }

    [ServerRpc]
    void JumpServerRpc()
    {
        Debug.Log("Server: Player jumped");
        PlayJumpSoundClientRpc();
    }

    [ClientRpc]
    void PlayJumpSoundClientRpc()
    {
        Debug.Log("Client: Play jump sound");
    }
}
OutputSuccess
Important Notes

Only the player who owns the object should call ServerRpc to avoid errors.

ServerRpc methods run on the server, ClientRpc methods run on all clients.

RPCs help keep multiplayer games in sync by sharing actions across devices.

Summary

Remote procedure calls let devices ask each other to run code.

Use [ServerRpc] for client-to-server calls.

Use [ClientRpc] for server-to-client calls.