I’m making an FPS game, and right now just want a placeholder UI for player health.
In order to do this I’m following this tutorial. I also added a health regen mechanic to keep things interesting.
Here is my code:
public class PlayerHealth : NetworkBehaviour
{
public const int maxHealth = 100;
[SyncVar(hook = "OnChangeHealth")]
public int currentHealth = maxHealth;
public RectTransform healthBar;
void Start()
{
InvokeRepeating ("RegenHealth", 0.0f, 1.0f);
}
public void TakeDamage(int amount)
{
if (!isServer) {
return;
}
currentHealth -= amount;
if (currentHealth <= 0) {
currentHealth = 100;
//Debug.Log("Dead!");
GetComponent<NetworkedPlayerScript> ().RpcResolveFall ();
}
//healthBar.sizeDelta = new Vector2 (currentHealth, healthBar.sizeDelta.y);
}
void RegenHealth()
{
if (currentHealth < maxHealth) {
currentHealth += 5;
}
}
void OnChangeHealth(int health)
{
healthBar.sizeDelta = new Vector2 (health, healthBar.sizeDelta.y);
}
}
To be clear, the actual health syncs from player to player. It is the health bar itself that is causing some issues. For example, when a host hits a client, both the client and host’s health bar goes down. When the client hits the host, neither health bar changes.
Am I missing something here? The health bar is a canvas attached to the player if that clears anything up. I’m just honestly so confused as why this doesn’t work. Since the actual health syncs up, I’d imagine getting a health bar to work would be easy. Any suggestions are welcome!