Unity携程Coroutine用法

news/2024/9/19 19:03:10 标签: unity, 游戏引擎

一.携程概述

官方的解释是,携程允许你可以在多个帧中执行任务。在Unity中,携程是一个可以暂停并在后续帧中从暂停处继续执行的方法。

二.携程写法

下面示例使用携程和Update打印前5帧的时间间隔,展示了携程的基础写法

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

public class demo2 : MonoBehaviour
{
    private int frameNum = 1;
    void Start()
    {
        StartCoroutine("coroutine");
    }

    public IEnumerator coroutine()
    {
        Debug.Log("coroutine frame1:" + Time.deltaTime);
        yield return null;
        Debug.Log("coroutine frame2:" + Time.deltaTime);
        yield return null;
        Debug.Log("coroutine frame3:" + Time.deltaTime);
        yield return null;
        Debug.Log("coroutine frame4:" + Time.deltaTime);
        yield return null;
        Debug.Log("coroutine frame5:" + Time.deltaTime);
        yield return null;
    }
    void Update()
    {
        if (frameNum <= 5)
        {
            Debug.Log("------ Update:" + frameNum + "  " + Time.deltaTime);
            frameNum++;
        }
    }
}

  • 从打印结果来看,携程和Update一样会每帧调用一次
  • StartCoroutine用于开启携程
  • 返回值类型固定为IEnumerator
  • 返回值yield return null表示下一帧从此处之后开始执行,等同于yield return 一个数字

这里IEnumerator接口和yield关键字是C#的,不了解的可查看前两篇文章

三.Unity规定的携程返回值含义(标红的较为常用)

代码含义
yield return null;  yield retun x(x代表任意数字)下一帧再执行后续代码

yield return new WaitForSeconds(0.1f);

yield return new WaitForSecondsRealtime(0.1f); //不受timescale影响

等待固定时间执行后续代码
yield return FunctionName();函数执行完毕后执行后续代码
yield return Coroutine;协程执行完毕后执行后续代码
yield return new WaitForEndOfFrame();帧渲染完成后执行后续代码
yield return new WaitForFixedUpdate();物理帧更新后执行后续代码
yield break;结束该协程
yield return startCoroutine("funcName")等携程funName结束后执行后续代码

四.携程在事件函数中的执行顺序

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

public class demo1 : MonoBehaviour
{
    private bool logStart = true;
    void Start()
    {
        StartCoroutine("coroutine1");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            logStart = !logStart;
            Debug.Log(logStart);
        }
        if (logStart)
        {
            Debug.Log("-------------------");
            Debug.Log("Update:" + Time.deltaTime);
        }
    }
    void LateUpdate()
    {
        if (logStart)
        {
            Debug.Log("LateUpdate:" + Time.deltaTime);
        }
    }

    public IEnumerator coroutine1()
    {
        while (true)
        {
            if (Input.GetKeyDown(KeyCode.S))
            {
                yield break;
            }
            else
            {
                Debug.Log("coroutine1:" + Time.deltaTime);
                yield return null;
            }
        }
    }
}

从打印结果来看,携程在Update之后,LateUpdate之前执行,官网的事件函数示意图也说明了这一点

五.携程的作用

1.替代Update处理一些耗时,按帧执行的任务,避免Update过于复杂

2.处理调用耗时API(比如切换场景)完成后在做什么的情况

六.携程可以传参可以嵌套

下面例子演示了crt1等待crt2结束后再执行后续,并给crt2传递参数

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

public class demo2 : MonoBehaviour
{
    void Start()
    {
        StartCoroutine("crt1");
    }

    public IEnumerator crt1()
    {
        Debug.Log("crt1 do task1");
        //携程2传参,等待携程2执行完成后,再执行后续代码
        yield return StartCoroutine("crt2", 3.0f);
        Debug.Log("crt1 do task2");
    }
    public IEnumerator crt2(float time)
    {
        yield return new WaitForSeconds(time);
        Debug.Log("crt2 do task after " + time + "sec");
        yield return new WaitForSeconds(2);
        Debug.Log("crt2 finish");
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            StopCoroutine("crt2");
            Debug.Log("crt2 is stopped");
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            StopAllCoroutines();
            Debug.Log("All crt stopped");
        }
    }
}

七.停止携程

StopCoroutine("funcName");  //停止携程funcName
StopAllCoroutines();        //停止脚本内所有携程

http://www.niftyadmin.cn/n/5666001.html

相关文章

webgl入门(003):技术优势和性能优势

还是大剑师兰特&#xff1a;曾是美国某知名大学计算机专业研究生&#xff0c;现为航空航海领域高级前端工程师&#xff1b;CSDN知名博主&#xff0c;GIS领域优质创作者&#xff0c;深耕openlayers、leaflet、mapbox、cesium&#xff0c;canvas&#xff0c;webgl&#xff0c;ech…

MATLAB系列08:输入/输入函数

MATLAB系列08&#xff1a;输入/输入函数 8. 输入/输入函数8.1 函数textread8.2 关于load和save命令的进一步说明8.3 MATLAB文件过程简介8.4 文件的打开和关闭8.4.1 fopen函数8.4.2 fclose函数 8.5 二进制 I/O 函数8.5.1 fwrite 函数8.5.2 fread函数 8.6 格式化 I/O 函数8.6.1 f…

自定义Spring Security认证处理的完整解决方案

文章目录 1. 自定义认证成功处理器2. 自定义认证失败处理器3. 自定义登出成功处理器4. 自定义未认证用户访问处理器5. 完整的Web安全配置总结 在今天的开发过程中&#xff0c;安全性是不可或缺的一部分&#xff0c;而Spring Security作为Java开发中的一站式解决方案&#xff0c…

Vm软件安装_链接相机

工业相机的驱动连接 下载安装MVS MVS 客户端支持安装在 Windows XP/7/10 32/64bit&#xff0c;Linux 32/64bits 以及MacOS64bits操作系统上。本文以 Windows 系统为例进行介绍。 具体操作步骤如下&#xff1a; 请从海康机器人官网&#xff08;www.hikrobotics.com&#xff0…

重修设计模式-结构型-适配器模式

重修设计模式-结构型-适配器模式 将不兼容的接口转换为可兼容的接口&#xff0c;让原本由于接口不兼容而不能一起工作的类可以一起工作 适配器模式&#xff08;Adapter Pattern&#xff09;允许将一个类的接口变换成客户端所期待的另一种接口&#xff0c;从而使原本因接口不匹配…

【machine learning-六-supervise learning之线性回归模型】

监督学习之线性回归模型 线性回归模型线性模型回归模型 如何使用线性模型实现智能化预测呢寻找数据训练模型输入、特征、目标、预测值、模型代价函数 线性模型是人工智能监督学习中最广泛的应用&#xff0c;所以有必要先学习一下这个基础模型&#xff0c;做好基石。 线性回归模…

ICPC网络预选赛1G题

The Median of the Median of the Median - Problem - QOJ.ac 给定一个序列{ai},i从1到n,首先构造一个序列{bij},i和j同样是从1到n,bij表示{ai....aj}的中位数,然后再构造一个{cij},cij表示{bii.....bij.....b(i1,i1).......b(i1,j).......bjj}的中位数,最后要求输出序列{cij}…

[数据集][目标检测]红外微小目标无人机直升机飞机飞鸟检测数据集VOC+YOLO格式7559张4类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;7559 标注数量(xml文件个数)&#xff1a;7559 标注数量(txt文件个数)&#xff1a;7559 标注…