- Home /
Question by
kubabuko123 · Sep 20, 2019 at 04:10 PM ·
syncclient-serverhealth
Player Health not syncing for clients
Hi, I have searched for answer, but still nothing is working for me. Host can see other players health, but clients don't really read that syncvar... Maybe solution is easy, but I can't figure it out. Thanks in advance!
Ball that hits player (script):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class OrbBehaviour : NetworkBehaviour
{
public GameObject firer;
private float damage = 25f;
void Start()
{
RpcIgnoreCollision(firer, gameObject);
}
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
List<GameObject> players = new List<GameObject>(GameObject.FindGameObjectsWithTag("Player"));
if (firer != collision.gameObject && players.Contains(collision.gameObject))
{
CmdOrbHit(collision.gameObject);
}
}
[Command]
void CmdOrbHit(GameObject player)
{
Destroy(gameObject);
player.GetComponent<Health>().TakeDamage(damage);
}
[ClientRpc]
void RpcIgnoreCollision(GameObject object1, GameObject object2)
{
Physics.IgnoreCollision(object1.GetComponent<Collider>(), object2.GetComponent<Collider>());
}
}
Player Health (script):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Health : NetworkBehaviour
{
public const float defHealth = 100f;
[Range(0, 100)]
[SyncVar]
public float health;
private const float MAX_HEALTH = 100f;
private const float MIN_HEALTH = 0f;
public GameObject healthBar;
private GameObject bar;
void Start()
{
health = defHealth;
if (isLocalPlayer)
{
bar = Instantiate(healthBar);
bar.GetComponentInChildren<Text>().text = health.ToString();
}
}
void Update()
{
if (isLocalPlayer)
{
bar.GetComponentInChildren<Text>().text = health.ToString();
}
}
public void TakeDamage(float damage)
{
if (!isServer && isLocalPlayer)
{
return;
}
health -= damage;
health = Mathf.Clamp(health, MIN_HEALTH, MAX_HEALTH);
}
}
Comment