Hello, I am currently building a 2d multiplayer shooting game. I am trying to create a health script that syncs across every player’s screen. But it is not working. These are my problems:
- My health bar is not syncing
- The bullets don’t take damage for some players, but does for some. Why?
This is my Health script:
public Image fill;
public int startingHealth;
public GameObject DeadCanvas;
public float currentHealth = 1;
public bool Dead;
void Start() {
DeadCanvas = GameObject.Find(“DeadCanvas”);
Dead = false;
startingHealth = 100;
currentHealth = 1;
fill.fillAmount = 1;
SetHealth();
}
void Update()
{
SetHealth();
CheckDeath();
}
void CheckDeath()
{
if (currentHealth <= 0 && Dead != true)
{
Dead = true;
GameManager.instance.onPlayerKilledCallback.Invoke(gameObject.name, “Enemy”);
GameObject DeadCanvas = GameObject.Find(“DeadCanvas”);
gameObject.SetActive(false);
}
}
public void TakeDamage(float dmg)
{
bool done = false;
if (isServer)
{
RpcTakeDamage(dmg);
return;
done = true;
}
if (!isServer && !done)
{
CmdTakeDamage(dmg);
}
}
void SetHealth()
{
if (!isLocalPlayer)
{
fill.fillAmount = currentHealth;
}
}
[ClientRpc]
void RpcTakeDamage(float damage)
{
if (!isServer)
return;
var Damage = damage / startingHealth;
currentHealth -= Damage;
fill.fillAmount = currentHealth;
}
[Command]
void CmdTakeDamage(float damage)
{
var Damage = damage / startingHealth;
currentHealth -= Damage;
fill.fillAmount = currentHealth;
}
This is my bullet collision script(it’s attached to the bullet)
public float Damage = 0;
public Vector3 dir;
void Awake()
{
Destroy(gameObject, 2);
}
void FixedUpdate()
{
gameObject.GetComponent().AddForce(transform.right * 100);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.GetComponent())
{
float health = col.gameObject.GetComponent().currentHealth / 100;
col.gameObject.GetComponent().TakeDamage(Damage);
This part is basically checking if player has won, so don’t worry if it looks confusing…:
if (col.gameObject.GetComponent().currentHealth < health)
{
if (GameObject.Find(gameObject.name).GetComponent()()
{
GameObject.Find(gameObject.name).GetComponent().HasWon = true;
}
}
Destroy(gameObject, 0.01f);
}
}
I have already seen a lot of sites but none of them works! So please help me! Thanks.