- Home /
Prefab health always ends up negative
In my PlayerAttack class my attack method is supposed to damage the prefabs not instantly kill them. When I tried to debug the prefabs health shows up as negative when it supposed to start with 100.
{
bool canAttack = true; public int damage = 25; public float cooldown;
int enemyHealth;
GameObject enemyObj;
public GameObject prefab;
Health eHealth;
int enemyH;
void Start()
{
GameObject enemy = GameObject.FindWithTag("Enemy");
if (enemy != null)
{
enemyHealth = enemy.GetComponent<Health>().health;
}
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
if(canAttack)
{
Attack();
}
}
}
void Attack()
{
enemyH = enemyH - damage;
Debug.Log(enemyH);
StartCoroutine(AttackCooldown(cooldown));
if (enemyH <= 0)
{
Debug.Log("dead");
Destroy(enemyObj);
}
}
private void OnTriggerEnter(Collider other)
{
enemyObj = other.gameObject;
if (enemyObj.tag == "Enemy")
{
Health eHealth = enemyObj.GetComponent<Health>();
int enemyH = eHealth.GetComponent<Health>().health;
enemyH = 100;
Debug.Log("EnemyInRange");
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Enemy")
{
canAttack = false;
Debug.Log("Outside of range");
}
}
IEnumerator AttackCooldown(float cooldown)
{
canAttack = false;
Debug.Log("cant attck");
yield return new WaitForSeconds(cooldown);
canAttack = true;
Debug.Log("can attack");
}
}
Comment
Best Answer
Answer by Hellium · May 01 at 10:52 PM
I took the opportunity to clean your code.
CODE NOT TESTED
public int damage = 25;
public float cooldown;
private Health enemyHealth;
private bool inCooldown = false;
private bool CanAttack => inCooldown == false && enemyHealth != null;
void Update()
{
if(CanAttack && Input.GetMouseButtonDown(0))
{
Attack();
}
}
void Attack()
{
// Implement the Damage method responsible for decreasing the health
// & destroying the object if the health goes below 0
// **IN THE HEALTH CLASS ITSELF**
enemyHealth.Damage(damage);
StartCoroutine(AttackCooldown(cooldown));
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy") && other.gameObject.TryGetComponent(out Health newEnemyHealth))
{
enemyHealth = newEnemyHealth;
Debug.Log("Enemy In Range");
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Enemy") && other.GetComponent<Health>() == enemyHealth)
{
enemyHealth = null;
Debug.Log("Outside of range");
}
}
IEnumerator AttackCooldown(float cooldown)
{
inCooldown = true;
Debug.Log("Attack cooldown started");
yield return new WaitForSeconds(cooldown);
inCooldown = false;
Debug.Log("Attack cooldown elapsed");
}
Your answer