SkeletonAnimation.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
  30. #define NEW_PREFAB_SYSTEM
  31. #endif
  32. using UnityEngine;
  33. namespace Spine.Unity {
  34. #if NEW_PREFAB_SYSTEM
  35. [ExecuteAlways]
  36. #else
  37. [ExecuteInEditMode]
  38. #endif
  39. [AddComponentMenu("Spine/SkeletonAnimation")]
  40. [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonAnimation-Component")]
  41. public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent {
  42. #region IAnimationStateComponent
  43. /// <summary>
  44. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  45. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  46. public Spine.AnimationState state;
  47. /// <summary>
  48. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  49. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  50. public Spine.AnimationState AnimationState {
  51. get {
  52. Initialize(false);
  53. return this.state;
  54. }
  55. }
  56. private bool wasUpdatedAfterInit = true;
  57. #endregion
  58. #region Bone Callbacks ISkeletonAnimation
  59. protected event UpdateBonesDelegate _BeforeApply;
  60. protected event UpdateBonesDelegate _UpdateLocal;
  61. protected event UpdateBonesDelegate _UpdateWorld;
  62. protected event UpdateBonesDelegate _UpdateComplete;
  63. /// <summary>
  64. /// Occurs before the animations are applied.
  65. /// Use this callback when you want to change the skeleton state before animations are applied on top.
  66. /// </summary>
  67. public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } }
  68. /// <summary>
  69. /// Occurs after the animations are applied and before world space values are resolved.
  70. /// Use this callback when you want to set bone local values.
  71. /// </summary>
  72. public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
  73. /// <summary>
  74. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  75. /// Using this callback will cause the world space values to be solved an extra time.
  76. /// Use this callback if want to use bone world space values, and also set bone local values.</summary>
  77. public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
  78. /// <summary>
  79. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  80. /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
  81. /// This callback can also be used when setting world position and the bone matrix.</summary>
  82. public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
  83. #endregion
  84. #region Serialized state and Beginner API
  85. [SerializeField]
  86. [SpineAnimation]
  87. private string _animationName;
  88. /// <summary>
  89. /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized.
  90. /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary>
  91. public string AnimationName {
  92. get {
  93. if (!valid) {
  94. return _animationName;
  95. } else {
  96. TrackEntry entry = state.GetCurrent(0);
  97. return entry == null ? null : entry.Animation.Name;
  98. }
  99. }
  100. set {
  101. Initialize(false);
  102. if (_animationName == value) {
  103. TrackEntry entry = state.GetCurrent(0);
  104. if (entry != null && entry.loop == loop)
  105. return;
  106. }
  107. _animationName = value;
  108. if (string.IsNullOrEmpty(value)) {
  109. state.ClearTrack(0);
  110. } else {
  111. var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(value);
  112. if (animationObject != null)
  113. state.SetAnimation(0, animationObject, loop);
  114. }
  115. }
  116. }
  117. /// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary>
  118. public bool loop;
  119. /// <summary>
  120. /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary>
  121. /// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks>
  122. public float timeScale = 1;
  123. #endregion
  124. #region Runtime Instantiation
  125. /// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary>
  126. /// <returns>The newly instantiated SkeletonAnimation</returns>
  127. public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset,
  128. bool quiet = false) {
  129. return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset, quiet);
  130. }
  131. /// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary>
  132. /// <returns>The newly instantiated SkeletonAnimation component.</returns>
  133. public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset,
  134. bool quiet = false) {
  135. return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset, quiet);
  136. }
  137. #endregion
  138. /// <summary>
  139. /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary>
  140. public override void ClearState () {
  141. base.ClearState();
  142. if (state != null) state.ClearTracks();
  143. }
  144. /// <summary>
  145. /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary>
  146. /// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param>
  147. public override void Initialize (bool overwrite, bool quiet = false) {
  148. if (valid && !overwrite)
  149. return;
  150. base.Initialize(overwrite, quiet);
  151. if (!valid)
  152. return;
  153. state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
  154. wasUpdatedAfterInit = false;
  155. if (!string.IsNullOrEmpty(_animationName)) {
  156. var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName);
  157. if (animationObject != null) {
  158. state.SetAnimation(0, animationObject, loop);
  159. #if UNITY_EDITOR
  160. if (!Application.isPlaying)
  161. Update(0f);
  162. #endif
  163. }
  164. }
  165. }
  166. void Update () {
  167. #if UNITY_EDITOR
  168. if (!Application.isPlaying) {
  169. Update(0f);
  170. return;
  171. }
  172. #endif
  173. Update(Time.deltaTime);
  174. }
  175. /// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary>
  176. public void Update (float deltaTime) {
  177. if (!valid || state == null)
  178. return;
  179. wasUpdatedAfterInit = true;
  180. if (updateMode < UpdateMode.OnlyAnimationStatus)
  181. return;
  182. UpdateAnimationStatus(deltaTime);
  183. if (updateMode == UpdateMode.OnlyAnimationStatus)
  184. return;
  185. ApplyAnimation();
  186. }
  187. protected void UpdateAnimationStatus (float deltaTime) {
  188. deltaTime *= timeScale;
  189. skeleton.Update(deltaTime);
  190. state.Update(deltaTime);
  191. }
  192. protected void ApplyAnimation () {
  193. if (_BeforeApply != null)
  194. _BeforeApply(this);
  195. if (updateMode != UpdateMode.OnlyEventTimelines)
  196. state.Apply(skeleton);
  197. else
  198. state.ApplyEventTimelinesOnly(skeleton);
  199. if (_UpdateLocal != null)
  200. _UpdateLocal(this);
  201. skeleton.UpdateWorldTransform();
  202. if (_UpdateWorld != null) {
  203. _UpdateWorld(this);
  204. skeleton.UpdateWorldTransform();
  205. }
  206. if (_UpdateComplete != null) {
  207. _UpdateComplete(this);
  208. }
  209. }
  210. public override void LateUpdate () {
  211. // instantiation can happen from Update() after this component, leading to a missing Update() call.
  212. if (!wasUpdatedAfterInit) Update(0);
  213. base.LateUpdate();
  214. }
  215. }
  216. }