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.");
}
}
如:
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.");
}
}
相关文章推荐
- Lua协程(coroutine)程序运行分析
- Lua的协程(coroutine)简介
- unity实现多点触控代码
- python协程用法实例分析
- 在Unity中实现动画的正反播放代码
- Unity UGUI教程之实现滑页效果
- unity实现摄像头跟随
- 简述Python中的进程、线程、协程
- Boost asio的async_write函数输入日志标题
- 进程、线程、协程基本概念理解
- Unity3D上路_01-2D太空射击游戏
- Unity3D上路_02-第一视角射击游戏
- Unity3D上路_03-塔防游戏
- Unity3D上路_04-基础资源介绍
- Unity3D上路_05-网络相关
- Unity3D-5.3.5发布VR项目到Android
- 简述Python中的进程、线程、协程
- [软件资讯]Unity已支持将3D游戏导出成Flash
- ShaderLab: Pass
- Unity 武器拖尾效果