SoloAnimation.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using Animancer.Units;
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.Animations;
  7. using UnityEngine.Playables;
  8. namespace Animancer
  9. {
  10. /// <summary>Plays a single <see cref="AnimationClip"/>.</summary>
  11. ///
  12. /// <remarks>
  13. /// <para></para>
  14. /// <strong>Documentation:</strong>
  15. /// <see href="https://kybernetik.com.au/animancer/docs/manual/playing/component-types">
  16. /// Component Types</see>
  17. /// <para></para>
  18. /// <strong>Sample:</strong>
  19. /// <see href="https://kybernetik.com.au/animancer/docs/samples/fine-control/doors">Doors</see>
  20. /// </remarks>
  21. ///
  22. /// https://kybernetik.com.au/animancer/api/Animancer/SoloAnimation
  23. ///
  24. [AddComponentMenu(Strings.MenuPrefix + "Solo Animation")]
  25. [AnimancerHelpUrl(typeof(SoloAnimation))]
  26. [DefaultExecutionOrder(DefaultExecutionOrder)]
  27. public class SoloAnimation : MonoBehaviour, IAnimationClipSource
  28. {
  29. /************************************************************************************************************************/
  30. #region Fields and Properties
  31. /************************************************************************************************************************/
  32. /// <summary>Initialize before anything else tries to use this component.</summary>
  33. public const int DefaultExecutionOrder = -5000;
  34. /************************************************************************************************************************/
  35. [SerializeField, Tooltip("The Animator component which this script controls")]
  36. private Animator _Animator;
  37. /// <summary>[<see cref="SerializeField"/>]
  38. /// The <see cref="UnityEngine.Animator"/> component which this script controls.
  39. /// </summary>
  40. /// <remarks>
  41. /// If you need to set this value at runtime you are likely better off using a proper
  42. /// <see cref="AnimancerComponent"/>.
  43. /// </remarks>
  44. public Animator Animator
  45. {
  46. get => _Animator;
  47. set
  48. {
  49. _Animator = value;
  50. if (IsInitialized)
  51. Play();
  52. }
  53. }
  54. /************************************************************************************************************************/
  55. [SerializeField, Tooltip("The animation that will be played")]
  56. private AnimationClip _Clip;
  57. /// <summary>[<see cref="SerializeField"/>] The <see cref="AnimationClip"/> that will be played.</summary>
  58. /// <remarks>
  59. /// If you need to set this value at runtime you are likely better off using a proper
  60. /// <see cref="AnimancerComponent"/>.
  61. /// </remarks>
  62. public AnimationClip Clip
  63. {
  64. get => _Clip;
  65. set
  66. {
  67. _Clip = value;
  68. if (IsInitialized)
  69. Play();
  70. }
  71. }
  72. /// <summary><see cref="AnimationClip.length"/></summary>
  73. /// <remarks>
  74. /// This value is cached on startup
  75. /// and is <see cref="float.NaN"/> if there's no <see cref="Clip"/>.
  76. /// </remarks>
  77. public float Length { get; private set; } = float.NaN;
  78. /// <summary><see cref="Motion.isLooping"/></summary>
  79. /// <remarks>This value is cached on startup.</remarks>
  80. public bool IsLooping { get; private set; }
  81. /************************************************************************************************************************/
  82. /// <summary>
  83. /// Should disabling this object stop and rewind the animation?
  84. /// Otherwise, it will simply be paused and will resume from its current state when re-enabled.
  85. /// </summary>
  86. /// <remarks>
  87. /// The default value is true.
  88. /// <para></para>
  89. /// This property inverts <see cref="Animator.keepAnimatorStateOnDisable"/>
  90. /// and is serialized by the <see cref="UnityEngine.Animator"/>.
  91. /// </remarks>
  92. public bool StopOnDisable
  93. {
  94. get => !_Animator.keepAnimatorStateOnDisable;
  95. set => _Animator.keepAnimatorStateOnDisable = !value;
  96. }
  97. /************************************************************************************************************************/
  98. /// <summary>The <see cref="PlayableGraph"/> being used to play the <see cref="Clip"/>.</summary>
  99. private PlayableGraph _Graph;
  100. /// <summary>The <see cref="AnimationClipPlayable"/> being used to play the <see cref="Clip"/>.</summary>
  101. private AnimationClipPlayable _Playable;
  102. /************************************************************************************************************************/
  103. private bool _IsPlaying;
  104. /// <summary>Is the animation playing (true) or paused (false)?</summary>
  105. public bool IsPlaying
  106. {
  107. get => _IsPlaying;
  108. set
  109. {
  110. _IsPlaying = value;
  111. if (value)
  112. {
  113. if (!IsInitialized)
  114. {
  115. Play();
  116. }
  117. else
  118. {
  119. _Graph.Play();
  120. #if UNITY_EDITOR
  121. // In Edit Mode, unpausing the graph doesn't work properly unless we force it to change.
  122. if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
  123. _Graph.Evaluate(0.00001f);
  124. #endif
  125. }
  126. }
  127. else
  128. {
  129. if (IsInitialized)
  130. _Graph.Stop();
  131. }
  132. }
  133. }
  134. /************************************************************************************************************************/
  135. [SerializeField, Range(0, 1)]
  136. [Tooltip("The normalized time that the animation will start at")]
  137. private float _NormalizedStartTime;
  138. /// <summary>[<see cref="SerializeField"/>] The normalized time that the animation will start at.</summary>
  139. public float NormalizedStartTime
  140. {
  141. get => _NormalizedStartTime;
  142. set => _NormalizedStartTime = value;
  143. }
  144. /************************************************************************************************************************/
  145. /// <summary>[<see cref="SerializeField"/>]
  146. /// The number of seconds that have passed since the start of the animation.
  147. /// </summary>
  148. /// <remarks>
  149. /// This value will continue increasing after the animation passes the end of its length
  150. /// and it will either freeze in place or start again from the beginning according to
  151. /// whether it's looping or not.
  152. /// </remarks>
  153. public float Time
  154. {
  155. get => _Playable.IsValid()
  156. ? (float)_Playable.GetTime()
  157. : _NormalizedStartTime * Length;
  158. set
  159. {
  160. if (_Playable.IsValid())
  161. SetTime(value);
  162. }
  163. }
  164. /// <summary>
  165. /// Calls <see cref="PlayableExtensions.SetTime{U}"/> twice
  166. /// to ensure that animation events aren't triggered incorrectly.
  167. /// </summary>
  168. private void SetTime(double value)
  169. {
  170. _Playable.SetTime(value);
  171. _Playable.SetTime(value);
  172. }
  173. /// <summary>[<see cref="SerializeField"/>]
  174. /// The <see cref="Time"/> of this state as a portion of the <see cref="AnimationClip.length"/>,
  175. /// meaning the value goes from 0 to 1 as it plays from start to end,
  176. /// regardless of how long that actually takes.
  177. /// </summary>
  178. /// <remarks>
  179. /// This value will continue increasing after the animation passes the end of its length
  180. /// and it will either freeze in place or start again from the beginning according to
  181. /// whether it's looping or not.
  182. /// <para></para>
  183. /// The fractional part of the value (<c>NormalizedTime % 1</c>) is the percentage (0-1)
  184. /// of progress in the current loop while the integer part (<c>(int)NormalizedTime</c>)
  185. /// is the number of times the animation has been looped.
  186. /// </remarks>
  187. public float NormalizedTime
  188. {
  189. get => _Playable.IsValid()
  190. ? (float)_Playable.GetTime() / Length
  191. : _NormalizedStartTime;
  192. set
  193. {
  194. if (_Playable.IsValid())
  195. SetTime(value * Length);
  196. }
  197. }
  198. /************************************************************************************************************************/
  199. [SerializeField, Multiplier, Tooltip("The speed at which the animation plays (default 1)")]
  200. private float _Speed = 1;
  201. /// <summary>[<see cref="SerializeField"/>] The speed at which the animation is playing (default 1).</summary>
  202. /// <exception cref="ArgumentException">This component is not yet <see cref="IsInitialized"/>.</exception>
  203. public float Speed
  204. {
  205. get => _Speed;
  206. set
  207. {
  208. _Speed = value;
  209. if (_Playable.IsValid())
  210. _Playable.SetSpeed(value);
  211. }
  212. }
  213. /************************************************************************************************************************/
  214. /// <summary>Indicates whether the <see cref="PlayableGraph"/> is valid.</summary>
  215. public bool IsInitialized
  216. => _Graph.IsValid();
  217. /************************************************************************************************************************/
  218. #endregion
  219. /************************************************************************************************************************/
  220. #if UNITY_EDITOR
  221. /************************************************************************************************************************/
  222. [SerializeField, Tooltip("Should the " + nameof(Clip) + " be automatically applied to the object in Edit Mode?")]
  223. private bool _ApplyInEditMode;
  224. /// <summary>[Editor-Only] Should the <see cref="Clip"/> be automatically applied to the object in Edit Mode?</summary>
  225. public ref bool ApplyInEditMode
  226. => ref _ApplyInEditMode;
  227. /************************************************************************************************************************/
  228. /// <summary>[Editor-Only]
  229. /// Tries to find an <see cref="UnityEngine.Animator"/> component on this <see cref="GameObject"/> or its
  230. /// children or parents (in that order).
  231. /// </summary>
  232. /// <remarks>
  233. /// Called by the Unity Editor when this component is first added (in Edit Mode) and whenever the Reset command
  234. /// is executed from its context menu.
  235. /// </remarks>
  236. protected virtual void Reset()
  237. {
  238. gameObject.GetComponentInParentOrChildren(ref _Animator);
  239. }
  240. /************************************************************************************************************************/
  241. /// <summary>[Editor-Only]
  242. /// Applies the <see cref="Speed"/>, <see cref="FootIK"/>, and <see cref="ApplyInEditMode"/>.
  243. /// </summary>
  244. /// <remarks>Called in Edit Mode whenever this script is loaded or a value is changed in the Inspector.</remarks>
  245. protected virtual void OnValidate()
  246. {
  247. if (!UnityEditor.EditorApplication.isPlaying)
  248. {
  249. if (_ApplyInEditMode && enabled)
  250. {
  251. if (!IsInitialized)
  252. {
  253. Play();
  254. IsPlaying = false;
  255. _Graph.Evaluate();
  256. }
  257. if (NormalizedTime != _NormalizedStartTime)
  258. {
  259. NormalizedTime = _NormalizedStartTime;
  260. _Graph.Evaluate();
  261. }
  262. }
  263. else
  264. {
  265. if (IsInitialized)
  266. _Graph.Destroy();
  267. }
  268. }
  269. if (IsInitialized)
  270. Speed = Speed;
  271. }
  272. /************************************************************************************************************************/
  273. #endif
  274. /************************************************************************************************************************/
  275. /// <summary>Plays the <see cref="Clip"/>.</summary>
  276. public void Play()
  277. => Play(_Clip);
  278. /// <summary>Plays the `clip`.</summary>
  279. public void Play(AnimationClip clip)
  280. {
  281. if (clip == null)
  282. {
  283. Length = 0;
  284. IsLooping = false;
  285. return;
  286. }
  287. Length = clip.length;
  288. IsLooping = clip.isLooping;
  289. if (_Animator == null)
  290. return;
  291. if (_Graph.IsValid())
  292. _Graph.Destroy();
  293. _Playable = AnimationPlayableUtilities.PlayClip(_Animator, clip, out _Graph);
  294. _Playable.SetSpeed(_Speed);
  295. SetTime(_NormalizedStartTime * Length);
  296. if (_Speed != 0)
  297. {
  298. _IsPlaying = true;
  299. }
  300. else
  301. {
  302. _IsPlaying = false;
  303. _Graph.Stop();
  304. }
  305. }
  306. /************************************************************************************************************************/
  307. /// <summary>Calls <see cref="PlayableGraph.Evaluate()"/>.</summary>
  308. public void Evaluate()
  309. {
  310. if (_Graph.IsValid())
  311. _Graph.Evaluate();
  312. }
  313. /// <summary>Calls <see cref="PlayableGraph.Evaluate(float)"/>.</summary>
  314. public void Evaluate(float deltaTime)
  315. {
  316. if (_Graph.IsValid())
  317. _Graph.Evaluate(deltaTime);
  318. }
  319. /************************************************************************************************************************/
  320. /// <summary>Plays the <see cref="Clip"/> on the target <see cref="Animator"/>.</summary>
  321. protected virtual void OnEnable()
  322. {
  323. if (!_IsPlaying)
  324. Play();
  325. }
  326. /************************************************************************************************************************/
  327. /// <summary>
  328. /// Checks if the animation is done
  329. /// so it can pause the <see cref="PlayableGraph"/> to improve performance.
  330. /// </summary>
  331. protected virtual void LateUpdate()
  332. {
  333. if (!IsPlaying ||
  334. IsLooping ||
  335. !_Playable.IsValid())
  336. return;
  337. var time = (float)_Playable.GetTime();
  338. if (_Speed >= 0)
  339. {
  340. if (time >= Length)
  341. {
  342. IsPlaying = false;
  343. Time = Length;
  344. }
  345. }
  346. else
  347. {
  348. if (time <= 0)
  349. {
  350. IsPlaying = false;
  351. Time = 0;
  352. }
  353. }
  354. }
  355. /************************************************************************************************************************/
  356. /// <summary>Stops playing and rewinds if <see cref="StopOnDisable"/>.</summary>
  357. protected virtual void OnDisable()
  358. {
  359. if (!IsInitialized)
  360. return;
  361. _IsPlaying = false;
  362. _Graph.Stop();
  363. if (StopOnDisable)
  364. SetTime(0);
  365. }
  366. /************************************************************************************************************************/
  367. /// <summary>Ensures that the <see cref="PlayableGraph"/> is properly cleaned up.</summary>
  368. protected virtual void OnDestroy()
  369. {
  370. if (IsInitialized)
  371. _Graph.Destroy();
  372. }
  373. /************************************************************************************************************************/
  374. #if UNITY_EDITOR
  375. /// <summary>[Editor-Only] Ensures that the <see cref="PlayableGraph"/> is destroyed.</summary>
  376. ~SoloAnimation()
  377. {
  378. UnityEditor.EditorApplication.delayCall += OnDestroy;
  379. }
  380. #endif
  381. /************************************************************************************************************************/
  382. /// <summary>[<see cref="IAnimationClipSource"/>] Adds the <see cref="Clip"/> to the list.</summary>
  383. public void GetAnimationClips(List<AnimationClip> clips)
  384. {
  385. if (_Clip != null)
  386. clips.Add(_Clip);
  387. }
  388. /************************************************************************************************************************/
  389. }
  390. }