UnityMirror study notes (3) function calls between the server and the client, sending control commands to each other Command, ClientRpc, TargetRpc

Hits: 0

Mirror is a simple and efficient open source multiplayer network [framework] for Unity .
Official documentation link:

Send an instruction from the client to be called by the server


Mirror provides a feature Commandto perform remote control instructions from the client to the server.

The basic usage is to edit the attribute label before the function that needs to be [called remotely :]

void cmdRemoteFunction(){}

This method can pass parameters, as long as the parameters support (automatic serialization and deserialization). Of course, custom data types can also be passed as parameters through custom serialization and deserialization, which will be learned later


Let’s show this API with an example:

Modify the control script of the Cube written in the previous section, so that each time you press the space, it will change its color:
Here, in order to better see your own Cube, all the used Cinemachinecontrols can be deleted at will.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using Cinemachine;
public class PlayerController : NetworkBehaviour
    [SyncVar(hook = nameof(ColorChanged))]
    Color PlayerColor = Color.white;

    void CmdChangeColor(Color color){
        PlayerColor = color;

    Rigidbody rb;
    MaterialPropertyBlock prop;
    CinemachineVirtualCamera cv;

    void ColorChanged(Color oldColor, Color newColor){
        Debug.Log("Color Changed");
        prop.SetColor("_Color" ,newColor);

    private void Start() {
        rb = GetComponent<Rigidbody>();
        prop = new MaterialPropertyBlock();
            cv = GameObject.FindGameObjectWithTag("VCAM").GetComponent<CinemachineVirtualCamera>();
            cv.Follow = this.transform;
            cv.LookAt = this.transform;

    private void Update() {
        if(!isLocalPlayer) return;
            CmdChangeColor(PlayerColor == Color.white?Color.black:Color.white);


As shown in the figure, one is the host and the other is the client.
When you press the space bar on one of the clients, everyone can see that the color of the corresponding character has changed.

important point

There is a condition implicit here, that is, only if the role belongs to its own and sends the execution method instruction to the server, the server will execute the corresponding role script.
Otherwise, in the above example, pressing space will change the color of both squares. We can achieve this “otherwise”
by modifying Commandthe parameters:requiresAuthority
[Command(requiresAuthority = false)]

Send an instruction from the server to be called by the client


Mirror provides a feature ClientRpcto perform remote control instructions from the server to the client.
This means that the code in the function will not be executed on the server.

The basic usage is to edit the attribute tag before the method that needs to be executed on the client side:

void RpcRemoteFunction(){}

Send an instruction from the server to be called by the specified client

The above [Rpc] will be sent to the corresponding object of all clients for execution, and
sometimes it needs to be sent to the corresponding object of the specified client for execution.

A simple example,
Player A hits player B, and on player B's model,
Jumped out of the text UI of the amount of blood lost,
But we don't want player A to see the display of this text UI,
then only through the B entity on the client that is only sent to player B,
The command to display the deduction text is implemented.


[ TargetRpc ]
 void  TargetRemoteDamaged ( NetworkConnection target, int damage ) {}
 //The first parameter can be ignored and is sent to itself by default, that is, the client entity that calls this method

In the above example, when A calls B,
it is obvious that the channel mounted on the B object can be obtained NetworkIdentity,
through which the connection channel between the client of B and the server can be obtained NetworkIdentity.connectionToClient.
It is executed by the server as TargetRpcthe first parameter of the parameter, and it can only be sent to the B client.

Of course, if this parameter is not carried, it will be sent to yourself by default.


In the above example, I also read the official documents to understand the necessity of this approach.
All the examples will be explained with the official documents. Eight:

public class Player : NetworkBehaviour
    public int health;

    void CmdMagic(GameObject target, int damage)
        target.GetComponent<Player>().health -= damage;

        NetworkIdentity opponentIdentity = target.GetComponent<NetworkIdentity>();
        TargetDoMagic(opponentIdentity.connectionToClient, damage);

    public void TargetDoMagic(NetworkConnection target, int damage)
        // This will appear on the opponent's client, not the attacking player's
        Debug.Log($"Magic Damage = {damage}");

    // Heal thyself
    public void CmdHealMe()
        health += 10;

    public void TargetHealed(int amount)
        // No NetworkConnection parameter, so it goes to owner
        Debug.Log($"Health increased by {amount}");

Here is if you hurt the other party, let the other party’s client know that he is injured and lost some blood, and other clients don’t know that
if he recovers blood, only himself knows that he recovers blood, such as seeing the green particle animation effect, others can not see.

final note

[Command]Functions are called by the client object, and the content is executed by the server object,
[ClientRpc]and [TargetRpc]functions are called by the server object, and the content is executed by the client object.
There must be no confusion here, stay awake!

Leave a Reply

Your email address will not be published.