Unity C # coroutine Discussion

Coroutine: the name suggests is at the same time the main program is running, open another section of logic processing to assist in the implementation of the main program, in most cases I use coroutines to delay calling a function, a logic block to be executed has been circulating judge these two conditions please, always thought before the termination function when there is a coroutine drawbacks, now check the information, recorded:

1, a co-write printing the "Start" and wait for printing text logic behind the implementation process for 5 seconds after the start :( function calls.)

	IEnumerator Test()
    {
        Debug.Log("开始");
        yield return new WaitForSeconds(5f);
        Debug.Log("已经开始了 5s 了");
    }

2, call the coroutine
calling coroutine which can directly fill method name can also be used to call a string, the string must be provided that the method names and Association process consistent.
(Method) parameters directly fill in the name of the function

    private void Start()
    {
        StartCoroutine(Test());
    }

(Method B) as a parameter called string ctrip

	private void Start()
    {
        StartCoroutine("Test");
    }

3, terminate a coroutine:
(a method) If you open coroutine, using a coroutine function string calls, so you can end the execution of a coroutine.
Note: This method can only be terminated by the string as a parameter of the open coroutine coroutine! ! !

 	/// <summary>
    /// 终止一个以字符串为参数调起的协程
    /// </summary>
    void Stop()
    {
    	//用字符串代替函数名终止协程
        StopCoroutine("Test");
    }

(Method II) when you adjust the parameters to a function called from the coroutine, there are overloaded fill in StopCoroutine parameters can be a function name.
Note: The function named parameters coroutine terminates the coroutine, I have repeatedly tested do not work, the Internet has said that this is a drawback coroutine.

  	/// <summary>
    /// 终止一个协程
    /// </summary>
    void Stop()
    {
        //以协程的函数名为参数终止该协程,
        //注意:该方式在我这里始终不能实现,且用且珍重
        StopCoroutine(Test());
    }

(Method Three) If you do not want to use a string as a parameter to call Ctrip, so feel after debugging is not convenient, then you can start the coroutine recorded a Coroutine pass parameters to achieve, as follows:

	//用来记录协程的
	Coroutine mCoroutine = null;
	
    void Start()
    {
    	//开启协程时记录下来
        mCoroutine= StartCoroutine(Test());
    }
    /// <summary>
    /// 终止一个协程
    /// </summary>
    void Stop()
    {
    	//以Coroutine为参数终止协程
        StopCoroutine(mCoroutine);
    }
Published 14 original articles · won praise 0 · Views 408

Guess you like

Origin blog.csdn.net/a0_67/article/details/105394070