AnimationEventCache.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #if UNITY_EDITOR
  3. using System.Runtime.CompilerServices;
  4. using UnityEngine;
  5. namespace Animancer.Editor
  6. {
  7. /// <summary>[Editor-Only] Caches <see cref="AnimationClip.events"/> to reduce garbage allocations.</summary>
  8. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/AnimationEventCache
  9. ///
  10. public static class AnimationEventCache
  11. {
  12. /************************************************************************************************************************/
  13. private static readonly ConditionalWeakTable<AnimationClip, AnimationEvent[]>
  14. ClipToEvents = new();
  15. /************************************************************************************************************************/
  16. /// <summary>
  17. /// Returns the <see cref="AnimationClip.events"/> and caches the result to avoid allocating more memory with
  18. /// each subsequent call.
  19. /// </summary>
  20. public static AnimationEvent[] GetCachedEvents(this AnimationClip clip)
  21. {
  22. if (!ClipToEvents.TryGetValue(clip, out var events))
  23. {
  24. events = clip.events;
  25. ClipToEvents.Add(clip, events);
  26. }
  27. return events;
  28. }
  29. /************************************************************************************************************************/
  30. /// <summary>Clears the cache.</summary>
  31. public static void Clear()
  32. => ClipToEvents.Clear();
  33. /************************************************************************************************************************/
  34. /// <summary>Removes the `clip` from the cache so its events will be retrieved again next time.</summary>
  35. public static void Remove(AnimationClip clip)
  36. => ClipToEvents.Remove(clip);
  37. /************************************************************************************************************************/
  38. }
  39. }
  40. #endif