您的位置:首页 > 移动开发 > Unity3D

Unity中协程的运行

2016-06-08 10:26 791 查看
在协程中搭配一个while循环,可以促使携程在多个帧数中运行,而不是一帧中就运行完成
如:

private IEnumerator _GameOver()
    {
        isGameOver = true;
        StartCoroutine(ScreenShake.Shake(theGame, 0.1f));
        while (ScreenShake.isShaking)
        {
            yield return true;
            Debug.Log("我是while循环");
        }
        SceneManager.LoadScene(0);
       // 使用While循环的好处就是可以在所谓的分线程中把ScreenShake.Shake()函数需要的效果处理完成,而不至于很快的在一帧中就跳过,导致达不到想要的效果
       /* yield return false;
        Debug.Log("运行次数");*/
    }

第一个Debug.log()在多个帧频中输出多个我是While循环
第二个Debug。log()只输出一帧,运行次数只输出一个;
使用协程的例子:

using UnityEngine;
using System.Collections;

public class CoroutinesExample : MonoBehaviour
{
    public float smoothing = 1f;
    public Transform target;

    void Start ()
    {
        StartCoroutine(MyCoroutine(target));
    }

    IEnumerator MyCoroutine (Transform target)
    {
        while(Vector3.Distance(transform.position, target.position) > 0.05f)
        {
            transform.position = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);

            yield return null;//等待下一帧继续运行协程,意思就是当第一次执行到这里的时候,返回到协程开始处,再次判断while循环语句的条件,每帧移动一点,直到不符合while条件,yield return null 的作用就是保证这个移动的过程不是瞬间就完成,而是在多个帧频中运行完成
        }

        print("Reached the target.");

        yield return new WaitForSeconds(3f);//等待三秒后运行协程,此处可以注释,也能达到想要的效果

        print("MyCoroutine is now finished.");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity 协程