美文网首页Unity
Unity之协程

Unity之协程

作者: 光明程辉 | 来源:发表于2017-03-07 16:04 被阅读27次

协程,又称微线程,纤程。英文名Coroutine。
子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B在执行过程中又调用了C,C执行完毕返回,B执行完毕返回,最后是A执行完毕。

因为协程是一个线程执行,那怎么利用多核CPU呢?最简单的方法是多进程+协程,既充分利用多核,又充分发挥协程的高效率,可获得极高的性能。

1、参数说明:

IEnumerator:协同程序的返回值类型;
yield return:协同程序返回 xxxxx;
new WaitForSeconds (秒数):实例化一个对象,等待多少秒后继续执行。 这个 Task3()的作用就是等待两秒后,继续执行任务 3.

2.开启协同程序

StartCoroutine(“协同程序方法名”);
这个 StartCoroutine 有三种重载形式,目前先只介绍这一种。

3.停止协同程序

StopCoroutine(“协同程序方法名”);
这个 StopCoroutine 也有三种重载形式,目前先只介绍这一种。

使用协程,实现一个 ♻️,移动。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BoxMove : MonoBehaviour {

private Vector3 v = new Vector3 ();
private float speed = 0.0375f;


void Start () {
    v.z = speed;

    StartCoroutine (Routine());
}

void Update () {
    
}


void FixedUpdate()
{
    transform.position += v;
}

//协程
IEnumerator Routine()
{
    v.z = speed;
    v.x = 0;

    yield return new WaitForSeconds (3f);
    v.z = 0;
    v.x = -speed;

    yield return new WaitForSeconds (3f);
    v.z = -speed;
    v.x = 0;

    yield return new WaitForSeconds (3f);
    v.z = 0;
    v.x = speed;
    yield return new WaitForSeconds (3f);

    StartCoroutine (Routine());
}
}
4.00.11.png

相关文章

  • XLua里使用协程

    在XLua里如何使用协程?有两种方式 使用Unity协程要想通过unity的StartCoroutine使用协程,...

  • Unity之协程

    协程,又称微线程,纤程。英文名Coroutine。子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B...

  • Unity 协程

    unity 里面的协程流程 开始协程 StartCoroutine("DoSomething"); 执行到 yie...

  • C#协程

    Unity中协程的执行原理 UnityGems.com给出了协程的定义: A coroutine is a fun...

  • unity协程

    今天在网上看见一个人的博客,发现对unity Coroutine有深入的了解分享一下 原文出处 unity Mo...

  • Unity3D 协程管理

    Unity里面的协程好用,但总是在如何关闭指定协程,尤其是关闭带参数的协程的问题上困惑不已。在本文,笔者带你用最简...

  • 自定义协程模块

    IFramework所有模块总目录 简介 协程在unity中很常见,IF中也有自己的协程。其本质就是通过:yiel...

  • Unity3d-仿写简单dotween C#扩展方法协程单例工厂

    dotween官网 先验知识:Unity3d-Coroutines协程 Unity3d-C#扩展方法 dotwee...

  • Unity协程(Coroutine)

    协程与线程的区别 1、协程不是线程,也不是异步执行的。2、协程和 MonoBehaviour 的 Update函数...

  • Unity的协程

    这篇文章转自:http://blog.csdn.net/huang9012/article/details/384...

网友评论

    本文标题:Unity之协程

    本文链接:https://www.haomeiwen.com/subject/lljkgttx.html