Question by
TIB69 · Jan 04 at 10:22 AM ·
damagecollision2dhealthbar
Can you guys help me with my health/damage system?
I've been trying to make this work for 2 days now, when i run it all hp goes down almost instantly, i think it s because the co routine is started every frame because it s in oncollisionstay2d but i couldn't find a solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthSystem : MonoBehaviour
{
public Image H1;
public Image H2;
public Image H3;
public Image H4;
private int hp = 4;
IEnumerator DamageResistance()
{
yield return new WaitForSeconds(1f);
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "enemy")
{
StartCoroutine(DamageResistance());
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.H))
{
hp -= 1;
}
if (hp == 3)
{
H4.color = new Vector4(255, 255, 255, 0);
}
if (hp == 2)
{
H4.color = new Vector4(255, 255, 255, 0);
H3.color = new Vector4(255, 255, 255, 0);
}
if (hp == 1)
{
H4.color = new Vector4(255, 255, 255, 0);
H3.color = new Vector4(255, 255, 255, 0);
H2.color = new Vector4(255, 255, 255, 0);
}
}
}
Comment