PlayAnimationOnClick.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value.
  3. using UnityEngine;
  4. namespace Animancer.Samples.Basics
  5. {
  6. /// <summary>
  7. /// Starts with an idle animation and performs an action when the user clicks the mouse, then returns to idle.
  8. /// </summary>
  9. ///
  10. /// <remarks>
  11. /// <strong>Sample:</strong>
  12. /// <see href="https://kybernetik.com.au/animancer/docs/samples/basics/action">
  13. /// Basic Action</see>
  14. /// </remarks>
  15. ///
  16. /// https://kybernetik.com.au/animancer/api/Animancer.Samples.Basics/PlayAnimationOnClick
  17. ///
  18. [AddComponentMenu(Strings.SamplesMenuPrefix + "Basics - Play Animation On Click")]
  19. [AnimancerHelpUrl(typeof(PlayAnimationOnClick))]
  20. public class PlayAnimationOnClick : MonoBehaviour
  21. {
  22. /************************************************************************************************************************/
  23. [SerializeField] private AnimancerComponent _Animancer;
  24. [SerializeField] private AnimationClip _Idle;
  25. [SerializeField] private AnimationClip _Action;
  26. /************************************************************************************************************************/
  27. protected virtual void OnEnable()
  28. {
  29. _Animancer.Play(_Idle);
  30. }
  31. /************************************************************************************************************************/
  32. protected virtual void Update()
  33. {
  34. if (SampleInput.LeftMouseUp)
  35. {
  36. // Play the action animation and grab the returned state which we can use to control it.
  37. AnimancerState state = _Animancer.Play(_Action);
  38. // Rewind the animation because Play doesn't do that automatically if it was already playing.
  39. state.Time = 0;
  40. // When the animation reaches its end, call OnEnable to go back to idle.
  41. state.Events(this).OnEnd ??= OnEnable;
  42. }
  43. }
  44. /************************************************************************************************************************/
  45. }
  46. }