SimpleAnimationPlayer.cs 2.3 KB

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