Unity~协程IEnumerator(简介)

版权声明:盗版必究 https://blog.csdn.net/jinxiul5/article/details/82114407
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class XIeChengScript : MonoBehaviour {
    float timer = 0;
       void Start () {
        //开启协程
        StartCoroutine(Test());
       }
       void Update () {
        //timer += Time.deltaTime;
        //if (timer>=1)
        //{
        //    timer = 0;
        //    Debug.Log("AAA");
        //}
       // Debug.Log("sss");

       }
    //协程 返回值为IEnumerator;
    //必须有yield return 加值;
    //开启协程StartCoroutine
    //代码只要遇到yield return 0 是就暂停,然后等到下一帧开始执行的时候从暂停的地方开始执行
    //1. 协程跟普通方法一样,可以多次调用
    //2.协程里的代码在在执行完后会自动退出协程,除非协程里有死循环\
    //3.代码只要遇到yield return 0 是就暂停,然后等到下一帧开始执行的时候从暂停的地方开始执行
    //4.遇到 yield return new WaitForSeconds(n);表示n秒后在向下执行其他的代码
    //5.yield return 后面可以调用一个新的协程,新的协程执行完以后在执行后面的代码;
    //6.如果yield return 后面跟了www类的一个对象,则该对象下载完成以后在执行后面的代码
    //7.开启协程也可以用StartCoroutine("协程方法名");
    //8.关闭协程使用StopCoroutine("协程方法名");只能这么写
    //9.协程可以有参数,但不能用ref或者out修饰
    IEnumerator Test( )
    {
        while (true)
        {
            Debug.Log("ttt");
            yield return new WaitForSeconds(1);
            Debug.Log("fff");
            yield return StartCoroutine(Run());
        }
    }
    IEnumerator Run( )
    {
        Debug.Log("RUN");
        yield return new WaitForSeconds(2);
        Debug.Log("RUN");
        yield return new WaitForSeconds(5);
    }
}

猜你喜欢

转载自blog.csdn.net/jinxiul5/article/details/82114407