This question was
closed Oct 10, 2021 at 12:02 PM by
GamingDuck for the following reason:
Too subjective and argumentative
Question by
GamingDuck · Oct 10, 2021 at 09:06 AM ·
enemy aifunctionsenemyaienemy damagehealth
Calling a function from another script causes it to be executed way too many times.
So I am trying to make my enemy hurt the player.
This is my Enemy script:
playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
if(Time.time > nextEnemyAttack)
{
Debug.Log("FIRED");
playerHealth.DamagePlayer(2);
float fireRate = 1;
nextEnemyAttack = Time.time + fireRate;
}
And this is my PlayerHealth script:
public int maxHealth;
private int health;
public void DamagePlayer(int damage)
{
if (armor > 0)
{
if (armor >= damage)
{
armor -= damage;
}
else if (armor < damage)
{
int remaningDamage;
remaningDamage = damage - armor;
armor = 0;
health -= remaningDamage;
}
}
else
{
health -= damage;
}
if (health <= 0)
{
Debug.Log("PLAYER DEAD");
Scene currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.buildIndex);
}
}
The problem I'm having is that when I call player.Health.DamagePlayer() in the Enemy script, it completely ignores the cooldown and runs every update. Everything works fine (the cooldown) when I don't call the DamagePlayer function, and the DamagePlayer works normally (runs once) if it is in a key press or something other than the cooldown. I have tried many ways of doing the cooldown and nothing seems to work. I'm pretty new to Unity and C# so all help is appreciated.
If anyone has any ideas please let me know, thanks :)
Comment