- Home /
SyncVar Hook not Updating after Client Joins
I'm having a bit of an issue. In my game, players control a little cube around that shoots, and I've recently implemented networking. Currently, I can't get my SyncVar for health to update as I want it to. I followed the recent tutorial on using the HLAPI and have since tried to transfer it into my game.
I'll try and run down my code, but there's quite a bit so I'll cut out all the non-essentials:
OnStartLocalPlayer I set my player's health to its max.
Whenever it takes damage i make sure the server does the calculation of the health (basically if isServer, then HP -= dam)
Now my HP variable is a SyncVar with the hook updateBar that should update the UI (using isLocalPlayer to be sure).
Problem: Whenever I'm just the host, everything works fine. I can run around, take some damage and it shows. Now I want to connect a client, and nothing works. The hosts' HP bar (not the HP, the bar) is reset, and the client cannot take damage. The host can take damage but it doesn't register.
Code:
[SyncVar(hook = "updateBar")]
public float HP;
public Image bar;
public Image shield;
public Text text;
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer>().material.color = Color.yellow;
camera.enabled = true;
HP = maxHP;
shields = 0f;
}
public void damage(float dam)
{
if (!isServer)
{
return;
}
if (shields > 0f)
{
if(dam > shields)
{
HP -= -(shields - dam);
shields = 0f;
}
else
{
shields -= dam;
}
}
else
{
HP -= dam;
}
//updateBar(HP);
checkHealth();
}
void updateBar(float val)
{
if(!isLocalPlayer)
{
return;
}
text.text = "" + Mathf.Floor(val + shields);
bar.rectTransform.anchoredPosition = Vector3.zero + Vector3.left * (100 - val / maxHP * 100);
}
private void checkHealth()
{
if (!isLocalPlayer)
{
return;
}
if (HP <= 0)
{
HP = 0f;
//updateBar(HP);
Camera.main.transform.parent = null;
manager.GetComponent<GameManager>().playerDeath();
Destroy(gameObject);
}
else if (HP > maxHP)
{
HP = maxHP;
}
if (shields <= 0f)
{
shields = 0f;
GetComponent<Light>().enabled = false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612123932im_/https://answers.unity.com/themes/thub/images/avi.jpg)