[SyncVar]
[SyncVar]
attribute is used to automatically synchronize variables from the server to clients. When the value changes on the server, it is automatically propagated to all clients.
Key Features
- One-way synchronization from server to client.
- Changes made on the client are not synchronized back to the server.
- Cannot be used with null values.
- Supports basic types (e.g., int, long, float, string, Vector3) and GameObject types that include a NetworkIdentity.
Basic Use
Syncing simple variables
public class Player : NetworkBehaviour
{
[SyncVar]
public int health = 100;
[SyncVar]
public string playerName = "Player";
[SyncVar]
public Vector3 spawnPoint;
}
Using Hook Functions
public class Player : NetworkBehaviour
{
[SyncVar(hook = nameof(OnHealthChanged))]
private int health = 100;
// The hook function takes the previous value and the new value as parameters.
private void OnHealthChanged(int oldValue, int newValue)
{
// Logic to execute when health changes
UpdateHealthUI(newValue);
PlayDamageEffect(oldValue - newValue);
}
}
Synchronizing GameObject with NetworkIdentity
public class PlayerEquipment : NetworkBehaviour
{
[SyncVar]
public GameObject currentWeapon; // Only GameObjects with NetworkIdentity can be synced
[Server]
public void EquipWeapon(GameObject weapon)
{
if (!weapon.GetComponent<NetworkIdentity>())
return;
currentWeapon = weapon;
}
}
Using Hook with GameObject
public class PlayerTeam : NetworkBehaviour
{
[SyncVar(hook = nameof(OnTeamChanged))]
public GameObject currentTeam; // GameObject with NetworkIdentity
private void OnTeamChanged(GameObject oldTeam, GameObject newTeam)
{
// Logic to execute when team changes
UpdateTeamUI();
UpdatePlayerColor();
}
}
note
- SyncVar values should only be changed on the server.
- Changing the SyncVar value on the client will not sync the value with other clients.
- The Hook function is automatically called whenever the value of a SyncVar changes.
- When using a GameObject as a SyncVar, the NetworkIdentity component is required. :::