Honkbark studios menu logo

StopCoroutine not working

Stopcoroutine not working

Please share this post with your friends

After playing around with StartCoroutine  to spawn different kind of game objects i had some trouble using StopCoroutine to halt the spawning. My first try was to use StopCoroutine right away, the same way that StartCoroutine is used:


using UnityEngine;
using System.Collections;

public class EnvironmentSpawner : MonoBehaviour {

	public GameObject LargeCloud;
  
	void Start() {
		StartCoroutine(SpawnLargeClouds());
	}
	
	void HaltSpawning() {
		StopCoroutine(SpawnLargeClouds());
	}

	IEnumerator SpawnLargeClouds() {
		yield return new WaitForSeconds(3);
		while(true) {
			var largeCloud = GameObjectPooler.Instance.GetObject(LargeCloud);
			largeCloud.transform.position = new Vector3(0.98f, 5.68f, -0f);
			largeCloud.transform.rotation = Quaternion.identity;
			largeCloud.SetActive(true);
			yield return new WaitForSeconds(3);
		}
	}
}

This will not work. To Use StopCoroutine there are two alternatives. The first alternative is to stop all Coroutines in the MonoBehaviour by using StopAllCoroutines();

This may however not be the wanted behaviour, there might be other coroutines that should continue to run. To accomplish this we need to keep a reference to the coroutine instance and use that to stop it:



using UnityEngine;
using System.Collections;

public class EnvironmentSpawner : MonoBehaviour {

	public GameObject LargeCloud;
  	private IEnumerator _LargeCloudsRoutine;

	void Start() {
		this._LargeCloudsRoutine = SpawnLargeClouds();
		StartCoroutine(this._LargeCloudsRoutine);
	}
	
	void HaltSpawning() {
		StopCoroutine(this._LargeCloudsRoutine);
	}

	IEnumerator SpawnLargeClouds() {
		yield return new WaitForSeconds(3);
		while(true) {
			var largeCloud = GameObjectPooler.Instance.GetObject(LargeCloud);
			largeCloud.transform.position = new Vector3(0.98f, 5.68f, -0f);
			largeCloud.transform.rotation = Quaternion.identity;
			largeCloud.SetActive(true);
			yield return new WaitForSeconds(3);
		}
	}
}

This technique is used in Friendsheep.

Categories: C#,Unity3D