- Home /
Simple network script not working?
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!
Should health = maxHealth; be health = newHealth;? Also, you are only syncing health, not maxHealth, is that correct?
I don't think so. And yeah, maxHealth is also a syncvar.
Yeah, my bad. Didn't notice you are already doing that. Hmmm..
Are you syncing the maxHealth before updating it so you say
Send max health over network
Increase maxhealth
when you would want it the other way around in that case.
What exactly do you mean? Currently maxhealth will be increased, and then the health will be set to that amount.
Answer by seanr · Nov 11, 2015 at 04:48 PM
The issue is that the hook for health is being called before the new value of maxHealth is applied on the client. This ordering is determined by the order the member variables are declared in the class.
If you switch the order that health and maxHealth are declared, then it works.
Answer by seanr · Nov 11, 2015 at 03:53 PM
you should post the entire script(s).
I $$anonymous$$ified the required classes and posted them here: http://hastebin.com/motanuxoza.avrasm. Thanks in advance!
Your answer
![](https://koobas.hobune.stream/wayback/20220612044629im_/https://answers.unity.com/themes/thub/images/avi.jpg)