{ Debug.Lo_unity 时间事件队列">
当前位置:   article > 正文

U3D游戏开发框架(九)——事件序列_unity 时间事件队列

unity 时间事件队列

一:目的

游戏开发中,经常会执行一连串的事件。例如在第2秒的时候播放攻击动画,在第5秒的时候播放走路动画,如果在上层类的Update中编写逻辑会增加代码冗余
所以我们需要一个事件序列类去统一管理


二:解决的问题及优点

——减少代码冗余


三:使用

——创建事件序列

s = new Sequence();

——添加事件序列

  1. s.AddEvent(0, () =>
  2. {
  3. Debug.Log("event1");
  4. });
  5. s.AddEvent(1, () =>
  6. {
  7. Debug.Log("event2");
  8. });
  9. s.AddEvent(2, () =>
  10. {
  11. Debug.Log("event3");
  12. });

——播放事件序列

s.Play();

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

s.Update(Time.deltaTime);

四:代码实现

  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 事件序列
  6. /// </summary>
  7. public class Sequence
  8. {
  9. /// <summary>
  10. /// 事件
  11. /// </summary>
  12. public class Event
  13. {
  14. public float eventTime;//事件时间
  15. public List<Action> eventList;//事件列表
  16. public Event(float eventTime)
  17. {
  18. this.eventTime = eventTime;
  19. eventList = new List<Action>();
  20. }
  21. public void Invoke()
  22. {
  23. foreach (var e in eventList)
  24. {
  25. e?.Invoke();
  26. }
  27. }
  28. }
  29. Dictionary<float, Event> eventOriginalCache = new Dictionary<float, Event>();//事件原始列表
  30. Dictionary<float, Event> eventPlayCache = new Dictionary<float, Event>();//事件播放列表(从事件原始列表拷贝一份)
  31. bool isPlaying;//序列是否在播放
  32. /// <summary>
  33. /// 播放事件序列
  34. /// </summary>
  35. public void Play()
  36. {
  37. if (isPlaying) return;
  38. CopyEvents();
  39. seqTimer = 0;
  40. isPlaying = true;
  41. }
  42. /// <summary>
  43. /// 添加事件
  44. /// </summary>
  45. public void AddEvent(float eventTime, Action customEvent)
  46. {
  47. if (!eventOriginalCache.ContainsKey(eventTime))
  48. {
  49. Event e = new Event(eventTime);
  50. eventOriginalCache.Add(eventTime, e);
  51. }
  52. eventOriginalCache[eventTime].eventList.Add(customEvent);
  53. }
  54. float seqTimer;//序列计时器
  55. List<float> delEventCache = new List<float>();//要删除的事件节点
  56. public void Update(float timeDelta)
  57. {
  58. if (!isPlaying) return;
  59. delEventCache.Clear();
  60. seqTimer += timeDelta;
  61. foreach (var temp in eventPlayCache)
  62. {
  63. if (seqTimer >= temp.Key)
  64. {
  65. Event sequenceEvent = temp.Value;
  66. sequenceEvent.Invoke();
  67. delEventCache.Add(temp.Key);
  68. }
  69. }
  70. foreach (var eventTime in delEventCache)
  71. {
  72. eventPlayCache.Remove(eventTime);
  73. }
  74. if (eventPlayCache.Count <= 0)
  75. {
  76. isPlaying = false;
  77. }
  78. }
  79. /// <summary>
  80. /// 拷贝事件
  81. /// </summary>
  82. void CopyEvents()
  83. {
  84. eventPlayCache.Clear();
  85. foreach (var temp in eventOriginalCache)
  86. {
  87. eventPlayCache.Add(temp.Key, temp.Value);
  88. }
  89. }
  90. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/761044
推荐阅读
相关标签
  

闽ICP备14008679号