Reputation: 59
I want the bullet to start a Coroutine in the enemy script, which damages the enemy every second by a float given to the enemy script from the bullet, until it reaches 0 hp and destroys itself. For some reason the "Poisoning" process works until the waitforseconds place. Do I miss something?
When testing debug.log("STEP ONE") is always reached without any problems. But "Poisoned" after the WaitForSecond moment is never reached. I do not have any other errors. The Bullet script works perfectly fine for non Poisonous bullets.
public class Enemy : MonoBehaviour
{
...
public IEnumerator Poisoned(float HpPerSecond)
{
Debug.Log("STEP ONE");
yield return new WaitForSeconds(1);
Debug.Log("Poisoned");
TakeDamage(HpPerSecond);
StartCoroutine(Poisoned(HpPerSecond));
}
...
}
public class Bullet : MonoBehaviour
{
public bool Poisonous = false;
public float PoisonDamagePerSecond;
Coroutine poison = null;
...
void DamageTarget()
{
...
if (Poisonous)
{
poison = StartCoroutine(target.GetComponent<Enemy>().Poisoned(PoisonDamagePerSecond));
}
...
}
...
}
Upvotes: 1
Views: 81
Reputation: 289
You need to understand about coroutines. Check out the official documentation at the following link.
void DamageTarget()
{
...
if (Poisonous)
{
poison = StartCoroutine(target.GetComponent<Enemy>().Poisoned(PoisonDamagePerSecond));
}
...
}
Coroutines run in MonoBehaviour by default.
If you write the code as above, the coroutine is executed in Bullet
.
When Bullet
is disabled or destroyed the coroutine stops.
Try working in the form below.
Enemy
public void StartPoisoned(float HpPerSecond)
{
StartCoroutine(Poisoned(HpPerSecond));
}
Bullet
void DamageTarget()
{
...
if (Poisonous)
{
target.GetComponent<Enemy>().StartPoisoned(PoisonDamagePerSecond));
}
...
}
Upvotes: 2