SimpleAnimationPlayer.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. using UnityEngine.Animations;
  3. using UnityEngine.Playables;
  4. namespace TriLibCore.Playables
  5. {
  6. /// <summary>Represents a Playable used to play Animations from its Animation Clip List using names or indices as parameters.</summary>
  7. public class SimpleAnimationPlayer : MonoBehaviour
  8. {
  9. /// <summary>
  10. /// Source animation clips.
  11. /// </summary>
  12. public AnimationClip[] AnimationClips;
  13. private PlayableGraph _playableGraph;
  14. private AnimationPlayableOutput _playableOutput;
  15. private AnimationClipPlayable _clipPlayable;
  16. private Animator _animator;
  17. private void Awake()
  18. {
  19. _animator = GetComponent<Animator>();
  20. }
  21. private void OnDestroy()
  22. {
  23. if (_playableGraph.IsValid())
  24. {
  25. _playableGraph.Destroy();
  26. }
  27. }
  28. /// <summary>Plays the Animation Clip with the given index.</summary>
  29. /// <param name="index">The Animation Clip index.</param>
  30. public void PlayAnimation(int index)
  31. {
  32. if (_animator == null || AnimationClips == null || index < 0 || index >= AnimationClips.Length)
  33. {
  34. return;
  35. }
  36. var animationClip = AnimationClips[index];
  37. if (_clipPlayable.IsValid())
  38. {
  39. _clipPlayable.Destroy();
  40. }
  41. _clipPlayable = AnimationPlayableUtilities.PlayClip(_animator, animationClip, out _playableGraph);
  42. _clipPlayable.SetApplyFootIK(false);
  43. _clipPlayable.SetApplyPlayableIK(false);
  44. }
  45. /// <summary>Plays the Animation Clip with the given index.</summary>
  46. /// <param name="name">The Animation Clip name.</param>
  47. public void PlayAnimation(string name)
  48. {
  49. if (_animator == null || AnimationClips == null)
  50. {
  51. return;
  52. }
  53. for (var i = 0; i < AnimationClips.Length; i++)
  54. {
  55. var animationClip = AnimationClips[i];
  56. if (animationClip.name == name)
  57. {
  58. PlayAnimation(i);
  59. }
  60. }
  61. }
  62. }
  63. }