How do I end a coroutine?

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?

You need to call StopCoroutine on the Enemy component of the enemy ship. The simplest way to do this would be to change line 8 to:

enemy.StopCoroutine("Fire");

However this is bad coding practice. Stopping coroutines on other GameObjects is asking for trouble down the track. A better method would be to have a public method on your Enemy component that calls StopCoroutine. Since you are already calling SetPositionAndSpeed…

public void SetPositionAndSpeed() {
    fireRate = Random.Range(3, 7);
    StopCoroutine("Fire");
    StartCoroutine("Fire");
}

You are not looking for the keyword ‘Break’, are you?
Or ‘Return’?

Hi I’m new to using Unity…

But would the InvokeRepeating function do what you want without using CoRoutines. →