I have a very basic health SyncVar in my PlayerStats class:
[SyncVar(hook = "OnHealthChange")]
public float health;
void OnHealthChange(float newHealth)
{
health = newHealth;
if (newHealth > maxHealth)
health = maxHealth;
if (newHealth <= 0)
health = 0;
}
In the Player class, there is a serialized reference to this class. In this class I have a simple script to display the health bar:
void OnGUI()
{
if (!isLocalPlayer)
return;
OfflineHealthBar.fillAmount = playerStats.health / playerStats.maxHealth;
OfflineHealthText.text = playerStats.health.ToString() + "/" + playerStats.maxHealth.ToString();
}
In another class, I have a server side method that increase the max health for the player, and automatically sets the current health to the max health:
case "UpgradeHealth":
playerStats.maxHealth += 50;
playerStats.health = playerStats.maxHealth;
break;
Everything works fine, however for some reason, when the players’ max health is increased, the players’ health won’t be updated. E.g. when a players’ max health increases from 1000 to 1050, the players’ health will still display as 1000 unless this process is repeated, then it will display 1050 while the max health is 1100.
This problem only occurs on a client. When I debug my health in the PlayerStats class, it will debug the right health. However, when I debug it in the Player class, it will debug the wrong health.
What am I doing wrong here? Thanks in advance!