I’m trying to make a script where an enemy ship shoots a projectile after a certain amount of time. If the enemy ship is hit by a user shot projectile before it has a chance to shoot then it doesn’t fire anything and is repositioned at the top of the screen.
Here’s the enemy ship Script.
public void SetPositionAndSpeed()
{
//sets position and speed of enemy ship.
fireRate = Random.Range(3, 7);
StartCoroutine("Fire");
}
IEnumerator Fire()
{
yield return new WaitForSeconds(fireRate);
Vector3 position = new Vector3(transform.position.x, transform.position.y + projectileOffset);
Instantiate(enemyProjectilePrefab, position, Quaternion.identity);
}
This is on the users projectile script.
void OnTriggerEnter2D(Collider2D otherObject)
{
if (otherObject.tag == "Enemy")
{
Enemy enemy = (Enemy)otherObject.gameObject.GetComponent("Enemy");
Instantiate(ExplosionPrefab, enemy.transform.position, enemy.transform.rotation);
StopCoroutine("Fire");
enemy.SetPositionAndSpeed();
// destroys projectile when contact is made and adds 100 points to score.
Destroy (gameObject);
Player.Score += 100;
}
The problem I’m facing here is the “StopCoroutine” function seems to be pausing the coroutine rather than ending it. So once the ship is repositioned it fires twice rather then once, which brings me to my question. How do I end a coroutine?