CodeBlanks Logo Icon CodeBlanks

Mirror networking

Learn SyncVar and Command structure with Mirror.

Mirror Networking and NetworkBehaviour

Mirror is an open-source, high-performance Client-Server networking library for Unity. Instead of standard MonoBehaviour, classes inherit from NetworkBehaviour.

using Mirror;

public class PlayerController : NetworkBehaviour {
    [SyncVar]
    public int health = 100;
}

When the server updates a variable tagged with the [SyncVar] attribute, Mirror automatically synchronizes the new value across all connected clients.

Client-to-Server Calls with [Command]

In an authoritative setup, clients cannot mutate game state directly. For a client to request an action on the server, a method tagged with the [Command] attribute is called.

// Called by client, executed strictly on the server
[Command]
public void CmdFireWeapon(Vector3 direction) {
    SpawnBulletOnServer(direction);
}

Command methods must begin with the Cmd prefix to make it immediately evident that a client request is being dispatched to the server.

Practice Print synchronized health value

Define a Start method. Inside, declare int health = 100; and print "Oyuncu cani senkron: " + health to the console using Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class MirrorPlayer : MonoBehaviour
{
    // Start icinde can ve SyncVar bilgisini yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class MirrorPlayer : MonoBehaviour
{
    void Start()
    {
        int health = 100;
        Debug.Log("Oyuncu cani senkron: " + health);
    }
}

Expected output

Oyuncu cani senkron: 100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which attribute in the Mirror library automatically synchronizes a variable's server value across all clients?

  • [SyncVar] Correct answer
  • [ClientRpc]
  • [TargetRpc]
  • [Command]

Explanation: [SyncVar] (Synchronized Variable) automatically syncs server-side value changes to each client's local copy.

2 Declare SyncVar

Question
[____] public int health = 100;
Answer
[SyncVar] public int health = 100;

Explanation: In Mirror, the '[SyncVar]' attribute is used for variable synchronization.

3 Mirror concepts

Term Meaning
NetworkBehaviour Base class for networked components
[SyncVar] Variable synced from server to clients
[Command] Method run by client on the server
CmdOnEk Mandatory prefix for Command functions

All lessons in Advanced