Using SyncVars to Sync Colors
Synchronizing color with synchronized variables!
Last updated
Synchronizing color with synchronized variables!
Last updated
We've got quite a few things synchronized now, but how would you synchronize a specific variable in one of your scripts? are one answer! A is a FishNet generic type that can be used within that automatically synchronize their value from the server to all clients.
Let's liven up the colors in our game and synchronize them with SyncVars.
Create a new script called SyncMaterialColor
. This will be used to synchronize the Material color of our MeshRenderers.
This simple script has a color
variable of the type SyncVar<Color>
. It should be set to readonly
, but we can still get and set its Value
.
In Awake
we subscribe to the SyncVar's OnChange
event. This event is very useful as it will be invoked as soon as the SyncVar changes, even on a client when the server changes it and it's synced.
OnColorChanged
is our method that we subscribed to the OnChange event. This method simply gets the MeshRenderer and sets its material color to the SyncVar's Color Value, thus updating the visuals to match on all devices.
Let's give the cubes some color now as soon as we instantiate them.
Reopen the PlayerCubeCreator.cs
script and make the following addition as show on line 24:
This line of code gets the SyncMaterialColor component and sets the SyncVar Value to a random color as soon as it's instantiated. Once Spawn is called on the next line, FishNet will spawn this object for all clients with the color SyncVar state synced.