M
M
Mirror
Search…
SyncVars
SyncVars are properties of classes that inherit from NetworkBehaviour, which are synchronized from the server to clients. When a game object is spawned, or a new player joins a game in progress, they are sent the latest state of all SyncVars on networked objects that are visible to them. Use the SyncVar custom attribute to specify which variables in your script you want to synchronize.
The state of SyncVars is applied to game objects on clients before OnStartClient() is called, so the state of the object is always up-to-date inside OnStartClient().
SyncVars can use any type supported by Mirror. You can have up to 64 SyncVars on a single NetworkBehaviour script, including SyncLists (see next section, below).
The server automatically sends SyncVar updates when the value of a SyncVar changes, so you do not need to track when they change or send information about the changes yourself. Changing a value in the inspector will not trigger an update.
The SyncVar hook attribute can be used to specify a method to be called when the SyncVar changes value on the client.

SyncVar Example

Let's say we have a networked object with a script called Enemy:
1
public class Enemy : NetworkBehaviour
2
{
3
[SyncVar]
4
public int health = 100;
5
6
void OnMouseUp()
7
{
8
NetworkIdentity ni = NetworkClient.connection.identity;
9
PlayerController pc = ni.GetComponent<PlayerController>();
10
pc.currentTarget = gameObject;
11
}
12
}
Copied!
The PlayerController might look like this:
1
public class PlayerController : NetworkBehaviour
2
{
3
public GameObject currentTarget;
4
5
void Update()
6
{
7
if (isLocalPlayer)
8
if (currentTarget != null &&currentTarget.tag == "Enemy")
9
if (Input.GetKeyDown(KeyCode.X))
10
CmdShoot(currentTarget);
11
}
12
13
[Command]
14
public void CmdShoot(GameObject enemy)
15
{
16
// Do your own shot validation here because this runs on the server
17
enemy.GetComponent<Enemy>().health -= 5;
18
}
19
}
Copied!
In this example, when a Player clicks on an Enemy, the networked enemy game object is assigned to PlayerController.currentTarget. When the player presses X, with a correct target selected, that target is passed through a Command, which runs on the server, to decrement the health SyncVar. All clients will be updated with that new value. You can then have a UI on the enemy to show the current value.

Class inheritance

SyncVars work with class inheritance. Consider this example:
1
class Pet : NetworkBehaviour
2
{
3
[SyncVar]
4
string name;
5
}
6
7
class Cat : Pet
8
{
9
[SyncVar]
10
public Color32 color;
11
}
Copied!
You can attach the Cat component to your cat prefab, and it will synchronize both it's name and color.
Warning Both Cat and Pet should be in the same assembly. If they are in separate assemblies, make sure not to change name from inside Cat directly, add a method to Pet instead.
Last modified 6mo ago