Unity3d 计时器、延时的三种方法 您所在的位置:网站首页 效果器延时调多少秒 Unity3d 计时器、延时的三种方法

Unity3d 计时器、延时的三种方法

2024-06-11 10:39| 来源: 网络整理| 查看: 265

计时器的三种方法 协程Time类InvokeRepeating

协程

协程是一个很好用的东西,它不是多线程,是一段主程序外的代码,它不受生命周期影响,每次都是在LateUpdate之后执行,也是通过条件来判断,满足条件的时候程序执行,可以做异步场景加载,不满足的时候挂起。

有两个语法: IEnumerator协程的返回值 yield return协程的判断条件

我们先建一个time脚本,挂在Canvas上面 完整代码

// An highlighted block using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class time : MonoBehaviour { private int hour;//小时 private int minute;//分钟 private int second;//秒 public Text timeshow; // Start is called before the first frame update void Start() { hour = 0; minute = 0; second = 0; StartCoroutine(showtime());//开启协程 } private IEnumerator showtime() { while (hour second = 0; minute++; } else if (minute > 60) { hour++; minute = 0; } else if (hour > 24) { hour = 0; } timeshow.text = hour + "时" + minute + "分" + second + "秒"; } } // Update is called once per frame void Update() { } }

看下效果 在这里插入图片描述

Time类

Time类主要用到的是Time.deltatime增量时间,它是每秒去执行,而不是每帧去执行。 1秒60帧就是增量时间的1/60秒,这个你们可以去看官网的说明

首先建一个time脚本,挂在Canvas上面

// An highlighted block using UnityEngine; using UnityEngine.UI; public class time : MonoBehaviour { private int hour;//小时 private int minute;//分钟 private int second;//秒 public Text timeshow; private float times;//定义一个数值 // Start is called before the first frame update void Start() { times = 0; } // Update is called once per frame void Update() { times += Time.deltaTime; if (times > 1f) { second++; times = 0; } else if (second > 60) { minute++; second = 0; } else if (minute > 60) { hour++; minute = 0; } timeshow.text = hour + "时" + minute + "分" + second + "秒"; } }

看下效果 在这里插入图片描述

InvokeRepeating

InvokeRepeating是一个函数,它的形式是这样的 InvokeRepeating(string,float,float_1);string代表回调函数,float代表多少秒后执行,float_1代表多少秒后重复调用前面的函数。

创建time脚本

// An highlighted block using UnityEngine; using UnityEngine.UI; public class time : MonoBehaviour { private int hour;//小时 private int minute;//分钟 private int second;//秒 public Text timeshow; void Start() { InvokeRepeating("Time",1f,1f); } private void Time() { second++; if (second > 60) { minute++; second = 0; } else if (minute > 60) { hour++; minute = 0; } timeshow.text = hour + "时" + minute + "分" + second + "秒"; } void Update() { } }

看下效果 在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有