Mirror/doc/articles/Classes/SyncVars.md

30 lines
1.3 KiB
Markdown
Raw Normal View History

2019-03-30 13:36:27 +00:00
# SyncVars
2019-06-26 00:28:06 +00:00
SyncVars are variables of scripts 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, like this:
2019-03-30 13:36:27 +00:00
2019-07-07 05:52:37 +00:00
```cs
2019-03-30 13:36:27 +00:00
class Player : NetworkBehaviour
{
[SyncVar]
int health;
public void TakeDamage(int amount)
{
if (!isServer)
return;
health -= amount;
}
}
```
2019-06-26 00:28:06 +00:00
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()`.
2019-03-30 13:36:27 +00:00
SyncVars can use any [type supported by Mirror](../Concepts/DataTypes.md). You can have up to 32 SyncVars on a single NetworkBehaviour script, including SyncLists (see next section, below).
2019-03-30 13:36:27 +00:00
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.
2019-03-30 14:20:02 +00:00
## SyncVar Hooks
The [SyncVar hook](SyncVarHook.md) attribute can be used to specify a method to be called when the SyncVar changes value on the client.