Table of Contents

SyncVars

SyncVars wrap a primative and automatically keep it in sync for all clients and the server

For example, to store "Health" on a Player, you can add a SyncVar as a field of your MyPlayer class

public partial class MyPlayer : Player
{
  public SyncVar<int> Health = new(100);
}

The Health variable can then be used normally:

public override void Update()
{
  Log.Info($"Player's health is: {Health}")

  if (Health <= 0)
  {
    Die();
  }
}

To change the value of a SyncVar use .Set():

public void TakeDamage()
{
  // SyncVars can only be updated from the server
  if (Network.IsServer)
  {
    Health.Set(Health - 10);
  }
}

The server and all clients will automatically receive the updated Health value.

Heads up! SyncVars .Set method can only be called on the server.

Heads up! You must call the constructor when declaring SyncVars (e.g. SyncVar<int> Health = new() is required. You may also provide an initial value inside the new()).

Type Support

SyncVars currently only support limited types like

  • int
  • float
  • bool
  • string
  • Vector2
  • Vector3
  • Vector4
  • Entity

We will also add enum support in the future, but in the mean time you can create a property to cast to/from your enum type e.g.:

  private SyncVar<int> currentRole = new((int)Role.JANITOR);
  public Role CurrentRole
  {
    get => (Role)currentRole.Value;
    set => currentRole.Set((int)value);
  }

OnSync

The OnSync method of a SyncVar is called any time the value of the SyncVar is updated (i.e. every time .Set() is called)

You don't need to use OnSync to use SyncVars, but it can be useful for performing "side effects" on the client, for example displaying a Notification to the user when their "cash" goes below a certain level.

  public SyncVar<int> Cash = new(125);

  public override void Start()
  {
    Cash.OnSync += (oldValue, newValue) =>
    {
      if (newValue < 20)
      {
        if (IsLocal)
        {
          Notifications.Show("You're about to run out of money!!");
        }
      }
    };
  }