Question by
mattbohinski0806 · Oct 31, 2019 at 12:00 PM ·
c#coroutinecoroutinesfor-loopcoroutine errors
Why isn't my coroutine working when I call it from another script.
Hello. For my senior year computer science class I get to do any computer science related project that I would like. I decided to make a game. In my game I need my player to come into contact with the enemy and do damage every 2 seconds. I am trying to use a coroutine but am having problems. If you can give me another way to solve the problem or help me with my coroutine that would be great.
This is where I call my coroutine:
public class PlayerDamage : MonoBehaviour { private PlayerHealthSyestem playerHealth; public bool isTrigger = false;
private void Awake()
{
playerHealth = GetComponent<PlayerHealthSyestem>();
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Enemy" && isTrigger==false)
{
isTrigger = true;
EnemyHealth enemy = collision.GetComponent<EnemyHealth>();
if (playerHealth != null)
{
//playerHealth.DelayMethodHere(enemy.damageAmount1);
StartCoroutine( playerHealth.DelayMethodHere(enemy.damageAmount1));
}
}
//else Debug.Log(collision.gameObject.name);
}
} This is where my coroutine runs:
public class PlayerHealthSyestem : MonoBehaviour { public int maxHealth = 100; public int currentHealth; public int damageAmount = 10; public bool alive = true;
private EnemyHealth enemy;
public void Start()
{
currentHealth = maxHealth;
Debug.Log("Player current health: " + currentHealth);
}
public IEnumerator DelayMethodHere(int enemyDamageAmount)
{
for (int i = 0; i < maxHealth / enemyDamageAmount; i++)
{
if (currentHealth <= 0)
{
alive = false;
Destroy(this.gameObject);
}
else
{
if (alive)
{
if (currentHealth > 1)
{
//StartCoroutine(DelayMethodHere(enemyDamageAmount));
currentHealth = currentHealth - (enemyDamageAmount);
alive = true;
}
}
}
yield return new WaitForSecondsRealtime(2f);
}
}
Comment