本文共 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 ListeventList;//事件列表 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;//事件计时器 ListdeleteEventNodeCache = 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); } }}
转载地址:http://hpyvf.baihongyu.com/