I have a player prefab with 1 field - energy, that is decreasing in random time (using Coroutines). When I run the game, all is working correctly, but when I add [SyncVar] to it, it starts to “jump”. Then I used hooks, and this is what i recieved:
The code is:
public class CatData : NetworkBehaviour
{
[SyncVar(hook = "OnEnergyChanged")]
private int energy;
public Transform energyBar;
void Start()
{
energy = 100;
StartCoroutine(Energy());
}
void Update()
{
energyBar.localScale = new Vector3((float)energy / 100 * 2.39f, energyBar.localScale.y, energyBar.localScale.z);
if (energy <= 0)
{
energy = 0;
}
if (energy > 100)
{
energy = 100;
}
}
void OnEnergyChanged(int value)
{
energy = value;
Debug.Log("Energy changed: " + energy);
}
IEnumerator Energy()
{
while (energy > 0)
{
yield return new WaitForSeconds(Random.Range(2, 5));
DecreaseEnergy(2, 10);
}
}
public void DecreaseEnergy(int min, int max)
{
energy -= Random.Range(min, max);
}
}
I’d like to know how to fix energy to work and sync properly