2018-10-17 协程 协同程序

协同程序简称“协程”。在脚本运行过程中,需要额外的执行一些其他的代码,

这个时候就可以将“其他代码”以协程的形式来运行。

类似于开启了一个线程,但是协程不是线程。

协同程序的使用前提

只有在继承了“MonoBehaviour”这个类的子类中才能使用相关的协程方法。

协同程序语法格式

协同程序就是一个代码片段,往往我们需要将这个代码片段封装成一个方法,或者称之为函数。

   IEnumerator test()
    {
        yield return new WaitForSeconds(2);
        Debug.Log("$");
    }

    IEnumerator test()
    {
        yield return new WaitForSeconds(2);
        Debug.Log("$");
    }

参数说明:

IEnumerator:协同程序的返回值类型;

yield return:协同程序返回 XXXX;

new WaitForSeconds(秒数):实例化一个对象,等待多少秒后执行。

Debug.log():这个就是等待多少秒后执行的任务。

开启协同程序

StartCoroutine("协同程序方法名");

停止协同程序

StopCoroutine("协同程序方法名");

void Start ()
	{
	    Debug.Log("1");
	    Debug.Log("2");
	    StartCoroutine("test");
	    Debug.Log("4");
	}
	
	// Update is called once per frame
	void Update () {
	    if (Input.GetKeyDown(KeyCode.Space))
	    {
	        StopCoroutine("test");
	    }
	}

    IEnumerator test()
    {
        yield return new WaitForSeconds(2);
        Debug.Log("$");
        yield return new WaitForSeconds(3);
        Debug.Log("$%");
    }

猜你喜欢

转载自blog.csdn.net/qq_31726339/article/details/83113710
今日推荐