Unity coroutine usage examples (remember to step on pit)

public class CoTest : MonoBehaviour 
{
	void Start () 
	{
		Invoke("Test1", 0.1f);
		Invoke("Test1", 0.2f);

		Invoke("Test2", 1.1f);
		Invoke("Test2", 1.2f);

		Invoke("Test3", 2.1f);
		Invoke("Test3", 2.2f);
		
		Invoke("Test4", 3.1f);
		Invoke("Test4", 3.2f);
	}

	// ----------------------------------------------

	void Test1()
	{
		StopCoroutine(Test1Co());
		StartCoroutine(Test1Co());
	}
	IEnumerator Test1Co()
	{
		yield return new WaitForSeconds(1);
		Debug.Log("Test1Co");
	}
	
	
	void Test2()
	{
		StopCoroutine("Test2Co");
		StartCoroutine(Test2Co());
	}
	IEnumerator Test2Co()
	{
		yield return new WaitForSeconds(1);
		Debug.Log("Test2Co");
	}

	// ----------------------------------------------

	void Test3()
	{
		StopCoroutine("Test3Co");
		StartCoroutine("Test3Co");
	}
	IEnumerator Test3Co()
	{
		yield return new WaitForSeconds(1);
		Debug.Log("Test3Co");
	}
	
	IEnumerator last4;
	void Test4()
	{
		if (last4 != null)
		{
			StopCoroutine(last4);
			last4 = null;
		}
		last4 = Test4Co();
		StartCoroutine(last4);
	}
	IEnumerator Test4Co()
	{
		yield return new WaitForSeconds(1);
		Debug.Log("Test4Co");
	}
}

Examples 1 and 2 above are pit, unable to stop in front of the coroutine
only examples 3 and 4 for the correct usage

 

The correct output is:

Test1Co

Test1Co

Test2Co

Test2Co

Test3Co

Test4Co

Guess you like

Origin blog.csdn.net/lsjsoft/article/details/89209748