Unity实现毫秒延时回调功能

Edana ·
更新时间:2024-09-20
· 24 次阅读

简介

在项目的框架中看到了这个延迟回调的函数,一直以为是通过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); } } } }

待更新

核心的功能很简单,但是最重要的是对tick的管理,不然每次遍历所有的任务是非常耗费性能的,根据时间的长短放入到不同对list中,这也是后续待更的内容。



回调 毫秒 unity

需要 登录 后方可回复, 如果你还没有账号请 注册新账号