简单记一下协程的使用

例子一

void  Update
{ 
        if (Input.GetKeyDown(KeyCode.S))
        {
            StartCoroutine("Waitforsecond");//开始某个协,括号里可以直接写协程名Waitforsecond(),参数的话
        }
} 

IEnumerator Waitforsecond()
    {
        Debug.Log("start");
        yield return StartCoroutine(wait(1f));
        Debug.Log("one second later");
        yield return StartCoroutine(wait(3f));
        Debug.Log("three seconds later");

    }

  这样打印结果依次为start,一秒后打印one second later,三秒后打印three seconds later。

 

  void Update ()
 {
        if (Input.GetKeyDown(KeyCode.A))
        { 
                StartCoroutine("begin", 5f);
            Debug.Log("begin");
        }
}

IEnumerator begin(float a)
    {
        while (true)
        {
            for (float timer=0; timer<1;timer+=Time.deltaTime)
            {
                yield return 0;
            }
            Debug.Log(seconds);
            seconds++;
           
            if (seconds > a)
            {
                StopCoroutine("begin");//停止某个协程, StopAllCoroutines();停止所有协程
                Debug.Log("stop");
            }
        }
    }

  打印结果为第0秒打印start,第一到六秒分别打印0—5,5打印之后立即打印stop.

程序遇到协程时会挂起,程序继续执行,然后等待下一帧,所以一开始按下A键之后先打印start。

 void Update () 
{
       
    if (Input.GetKeyDown(KeyCode.D))
        {
            StartCoroutine("movetotarget", new Vector3(3f,3f,3f));
        }
}
 IEnumerator movetotarget(Vector3 a)
    {
        while(transform.position!=a)
        {
            transform.position = Vector3.MoveTowards(transform.position, a, 3f*Time.deltaTime);
            yield return null;
        }
    }

例子二 

 在协程里写while循环就像是Update,每帧都会调用,运行后物体从原位置匀速移动到a位置

 private Vector3[] path = new Vector3[] 
    {
        new Vector3( 5f,0f,5f),
        new Vector3(0f,5f,5f),
        new Vector3(0,0,0),
    };

 void Update () 
{
      if (Input.GetKeyDown(KeyCode.F))
        {
            StartCoroutine("moveontheway");
        }
}

 IEnumerator moveontheway()
    {
        while (true)
        {
            foreach (Vector3 point in path)
            {
                yield return StartCoroutine("movetotarget",point);
                yield return StartCoroutine(wait(1f));
            }
            
        }
    }

  运行效果类似于守卫巡逻,物体移动到一个位置后等待一秒然后往下一个目标点移动,循环往复。

 

posted on 2017-06-03 17:30  懒人起烂名  阅读(311)  评论(0编辑  收藏  举报