AccumulatorUtility.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Fort23.Core;
  2. using UnityEngine;
  3. namespace Core.UI.UTool
  4. {
  5. public class AccumulatorUtility
  6. {
  7. public class AccumulationData
  8. {
  9. public float currentTotal;
  10. public float targetTotal;
  11. public float duration;
  12. public System.Action<float> onIncrement;
  13. public System.Action onComplete;
  14. }
  15. /// <summary>
  16. /// 开始精确累加
  17. /// </summary>
  18. public static async void StartAccumulation(int targetTotal, float duration, int steps,
  19. System.Action<int> onStep, System.Action onComplete = null)
  20. {
  21. int stepValue = targetTotal / (steps);
  22. float timePerStep = duration / steps;
  23. int currentTotal = 0;
  24. for (int i = 0; i < steps-1; i++)
  25. {
  26. await TimerComponent.Instance.WaitAsync((int)(timePerStep * 1000));
  27. currentTotal += stepValue;
  28. onStep?.Invoke(stepValue);
  29. }
  30. // 确保最终精度
  31. // currentTotal = targetTotal;
  32. onStep?.Invoke(targetTotal - currentTotal);
  33. onComplete?.Invoke();
  34. }
  35. /// <summary>
  36. /// 开始实时累加(基于Update)
  37. /// </summary>
  38. public static async void StartRealtimeAccumulation(AccumulationData data)
  39. {
  40. float timer = 0f;
  41. data.currentTotal = 0f;
  42. while (timer < data.duration)
  43. {
  44. timer += Time.deltaTime;
  45. float progress = timer / data.duration;
  46. float newTotal = progress * data.targetTotal;
  47. float increment = newTotal - data.currentTotal;
  48. if (increment > 0)
  49. {
  50. data.currentTotal = newTotal;
  51. data.onIncrement?.Invoke(data.currentTotal);
  52. }
  53. // yield return null;
  54. }
  55. data.currentTotal = data.targetTotal;
  56. data.onIncrement?.Invoke(data.currentTotal);
  57. data.onComplete?.Invoke();
  58. }
  59. }
  60. }