这篇文章主要为大家展示了“Unity如何实现毫秒延时回调功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Unity如何实现毫秒延时回调功能”这篇文章吧。
API
1: Time.deltaTime
实际上就是每帧所执行的时间
功能实现
简单的说一下功能的实现,下面会直接贴出源码。
每一个新增的任务(回调)都会记录创建任务的时间以及延迟的时间,以及自己的事件回调。通过每帧判断当前帧的时间是否大于创建的(任务的时间+延迟的时间)
代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TickManager : MonoBehaviour
{
// Start is called before the first frame update
public int NOW;
private List<Tick> _ticks = new List<Tick>();
private void Update()
{
//测试--手动创建一个5秒后的回调
if (Input.GetKeyDown(KeyCode.A))
{
Tick tick = new Tick(() =>
{
Debug.Log("任务执行");
},5000,NOW);
_ticks.Add(tick);
}
//每帧所使用的毫秒时间
uint deltaTime = (uint)(Time.deltaTime * 1000);
//遍历判断集合中的任务是否执行
for (int i = 0; i < deltaTime; i++)
{
Debug.Log("帧数 " + NOW);
for (int j = 0; j < _ticks.Count; j++)
{
_ticks[j].OnTick(NOW);
}
++NOW;
}
}
class Tick
{
//创建任务的时间
public int currentTime { get; set; }
//需要延迟的时间
public int delayTime { get; set; }
//延迟后的回调事件
public Action action { get; set; }
//构造函数--初始化
public Tick(Action ac, int del, int now)
{
action = ac;
delayTime = del;
currentTime = now;
}
//判断该任务是否执行
public void OnTick(int now)
{
if (now >= (currentTime + delayTime))
{
action();
}
else
{
Debug.Log("时间还未到 "+ now);
}
}
}
}
以上是“Unity如何实现毫秒延时回调功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!