U3D游戏开发框架(九)——事件序列
发布日期:2021-06-30 19:58:36 浏览次数:2 分类:技术文章

本文共 2141 字,大约阅读时间需要 7 分钟。

一:目的

游戏开发中,经常会执行一连串的事件。例如在第2秒的时候播放攻击动画,在第5秒的时候播放走路动画,如果在上层类的Update中编写逻辑会增加代码冗余

所以我们需要一个事件序列类去统一管理


二:解决的问题及优点

——减少代码冗余


三:使用

——创建事件序列

s = new Sequence();

——添加事件序列

s.AddEvent(0, () =>{    Debug.Log("event1");});s.AddEvent(1, () =>{    Debug.Log("event2");});s.AddEvent(2, () =>{    Debug.Log("event3");});

——播放事件序列

s.PlaySequence();

——在每帧刷新的方法中调用Update方法

s.Update(Time.deltaTime);

四:代码实现

using System;using System.Collections.Generic;using UnityEngine;/// /// 事件序列/// public class Sequence{    ///     /// 事件    ///     public class Event    {        public float eventTime;//事件时间        public List
eventList;//事件列表 public Event(float eventTime) { this.eventTime = eventTime; eventList = new List
(); } public void Invoke() { foreach (var e in eventList) { e?.Invoke(); } } } Dictionary
eventOriginalCache = new Dictionary
();//事件原始列表 Dictionary
eventPlayCache = new Dictionary
();//事件播放列表(从事件原始列表拷贝一份) bool isPlay;//是否播放序列 ///
/// 播放事件序列 /// public void PlaySequence() { if (isPlay) return; CopyEvents(); sequenceTimer = 0; isPlay = true; } ///
/// 添加事件 /// public void AddEvent(float eventTime, Action customEvent) { if (!eventOriginalCache.ContainsKey(eventTime)) { Event e = new Event(eventTime); eventOriginalCache.Add(eventTime, e); } eventOriginalCache[eventTime].eventList.Add(customEvent); } float sequenceTimer;//事件计时器 List
deleteEventNodeCache = new List
();//要删除的事件节点 public void Update(float timeDelta) { if (!isPlay) return; deleteEventNodeCache.Clear(); sequenceTimer += timeDelta; foreach (var temp in eventPlayCache) { if (sequenceTimer >= temp.Key) { Event sequenceEvent = temp.Value; sequenceEvent.Invoke(); deleteEventNodeCache.Add(temp.Key); } } foreach (var eventTime in deleteEventNodeCache) { eventPlayCache.Remove(eventTime); } if (eventPlayCache.Count <= 0) { isPlay = false; } } ///
/// 拷贝事件 /// void CopyEvents() { eventPlayCache.Clear(); foreach (var temp in eventOriginalCache) { eventPlayCache.Add(temp.Key, temp.Value); } }}

 

转载地址:https://liuhaowen.blog.csdn.net/article/details/117606327 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Unity中解决“SetDestination“ can only be called on an active agent that has been placed on a NavMesh
下一篇:Unity中实现反弹

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月27日 15时52分32秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章