Using SyncVars to Sync Colors
Synchronizing color with synchronized variables!
1
Creating a script to sync color
using FishNet.Object;
using FishNet.Object.Synchronizing;
using UnityEngine;
[RequireComponent(typeof(MeshRenderer))]
public class SyncMaterialColor : NetworkBehaviour
{
public readonly SyncVar<Color> Color = new SyncVar<Color>();
private void Awake()
{
Color.OnChange += OnColorChanged;
}
private void OnColorChanged(Color previous, Color next, bool asServer)
{
GetComponent<MeshRenderer>().material.color = Color.Value;
}
}3
Give the cubes random colors
obj.GetComponent<SyncMaterialColor>().Color.Value = Random.ColorHSV();using FishNet.Object;
using UnityEngine;
public class PlayerCubeCreator : NetworkBehaviour
{
public NetworkObject CubePrefab;
void Update()
{
// Only the local player object should perform these actions.
if (!IsOwner)
return;
if (Input.GetButtonDown("Fire1"))
SpawnCube();
}
// We are using a ServerRpc here because the Server needs to do all network object spawning.
[ServerRpc]
private void SpawnCube()
{
NetworkObject obj = Instantiate(CubePrefab, transform.position, Quaternion.identity);
obj.GetComponent<SyncMaterialColor>().Color.Value = Random.ColorHSV();
Spawn(obj); // NetworkBehaviour shortcut for ServerManager.Spawn(obj);
}
}Last updated

