BoundingBoxFollower.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. using System.Collections.Generic;
  34. namespace Spine.Unity {
  35. #if NEW_PREFAB_SYSTEM
  36. [ExecuteAlways]
  37. #else
  38. [ExecuteInEditMode]
  39. #endif
  40. public class BoundingBoxFollower : MonoBehaviour {
  41. internal static bool DebugMessages = true;
  42. #region Inspector
  43. public SkeletonRenderer skeletonRenderer;
  44. [SpineSlot(dataField: "skeletonRenderer", containsBoundingBoxes: true)]
  45. public string slotName;
  46. public bool isTrigger;
  47. public bool clearStateOnDisable = true;
  48. #endregion
  49. Slot slot;
  50. BoundingBoxAttachment currentAttachment;
  51. string currentAttachmentName;
  52. PolygonCollider2D currentCollider;
  53. public readonly Dictionary<BoundingBoxAttachment, PolygonCollider2D> colliderTable = new Dictionary<BoundingBoxAttachment, PolygonCollider2D>();
  54. public readonly Dictionary<BoundingBoxAttachment, string> nameTable = new Dictionary<BoundingBoxAttachment, string>();
  55. public Slot Slot { get { return slot; } }
  56. public BoundingBoxAttachment CurrentAttachment { get { return currentAttachment; } }
  57. public string CurrentAttachmentName { get { return currentAttachmentName; } }
  58. public PolygonCollider2D CurrentCollider { get { return currentCollider; } }
  59. public bool IsTrigger { get { return isTrigger; } }
  60. void Start () {
  61. Initialize();
  62. }
  63. void OnEnable () {
  64. if (skeletonRenderer != null) {
  65. skeletonRenderer.OnRebuild -= HandleRebuild;
  66. skeletonRenderer.OnRebuild += HandleRebuild;
  67. }
  68. Initialize();
  69. }
  70. void HandleRebuild (SkeletonRenderer sr) {
  71. //if (BoundingBoxFollower.DebugMessages) Debug.Log("Skeleton was rebuilt. Repopulating BoundingBoxFollower.");
  72. Initialize();
  73. }
  74. /// <summary>
  75. /// Initialize and instantiate the BoundingBoxFollower colliders. This is method checks if the BoundingBoxFollower has already been initialized for the skeleton instance and slotName and prevents overwriting unless it detects a new setup.</summary>
  76. public void Initialize (bool overwrite = false) {
  77. if (skeletonRenderer == null)
  78. return;
  79. skeletonRenderer.Initialize(false);
  80. if (string.IsNullOrEmpty(slotName))
  81. return;
  82. // Don't reinitialize if the setup did not change.
  83. if (!overwrite
  84. &&
  85. colliderTable.Count > 0 && slot != null // Slot is set and colliders already populated.
  86. &&
  87. skeletonRenderer.skeleton == slot.Skeleton // Skeleton object did not change.
  88. &&
  89. slotName == slot.data.name // Slot object did not change.
  90. )
  91. return;
  92. slot = null;
  93. currentAttachment = null;
  94. currentAttachmentName = null;
  95. currentCollider = null;
  96. colliderTable.Clear();
  97. nameTable.Clear();
  98. var skeleton = skeletonRenderer.skeleton;
  99. slot = skeleton.FindSlot(slotName);
  100. int slotIndex = skeleton.FindSlotIndex(slotName);
  101. if (slot == null) {
  102. if (BoundingBoxFollower.DebugMessages)
  103. Debug.LogWarning(string.Format("Slot '{0}' not found for BoundingBoxFollower on '{1}'. (Previous colliders were disposed.)", slotName, this.gameObject.name));
  104. return;
  105. }
  106. int requiredCollidersCount = 0;
  107. var colliders = GetComponents<PolygonCollider2D>();
  108. if (this.gameObject.activeInHierarchy) {
  109. foreach (var skin in skeleton.Data.Skins)
  110. AddCollidersForSkin(skin, slotIndex, colliders, ref requiredCollidersCount);
  111. if (skeleton.skin != null)
  112. AddCollidersForSkin(skeleton.skin, slotIndex, colliders, ref requiredCollidersCount);
  113. }
  114. DisposeExcessCollidersAfter(requiredCollidersCount);
  115. if (BoundingBoxFollower.DebugMessages) {
  116. bool valid = colliderTable.Count != 0;
  117. if (!valid) {
  118. if (this.gameObject.activeInHierarchy)
  119. Debug.LogWarning("Bounding Box Follower not valid! Slot [" + slotName + "] does not contain any Bounding Box Attachments!");
  120. else
  121. Debug.LogWarning("Bounding Box Follower tried to rebuild as a prefab.");
  122. }
  123. }
  124. }
  125. void AddCollidersForSkin (Skin skin, int slotIndex, PolygonCollider2D[] previousColliders, ref int collidersCount) {
  126. if (skin == null) return;
  127. var skinEntries = new List<Skin.SkinEntry>();
  128. skin.GetAttachments(slotIndex, skinEntries);
  129. foreach (var entry in skinEntries) {
  130. var attachment = skin.GetAttachment(slotIndex, entry.Name);
  131. var boundingBoxAttachment = attachment as BoundingBoxAttachment;
  132. if (BoundingBoxFollower.DebugMessages && attachment != null && boundingBoxAttachment == null)
  133. Debug.Log("BoundingBoxFollower tried to follow a slot that contains non-boundingbox attachments: " + slotName);
  134. if (boundingBoxAttachment != null) {
  135. if (!colliderTable.ContainsKey(boundingBoxAttachment)) {
  136. var bbCollider = collidersCount < previousColliders.Length ?
  137. previousColliders[collidersCount] : gameObject.AddComponent<PolygonCollider2D>();
  138. ++collidersCount;
  139. SkeletonUtility.SetColliderPointsLocal(bbCollider, slot, boundingBoxAttachment);
  140. bbCollider.isTrigger = isTrigger;
  141. bbCollider.enabled = false;
  142. bbCollider.hideFlags = HideFlags.NotEditable;
  143. bbCollider.isTrigger = IsTrigger;
  144. colliderTable.Add(boundingBoxAttachment, bbCollider);
  145. nameTable.Add(boundingBoxAttachment, entry.Name);
  146. }
  147. }
  148. }
  149. }
  150. void OnDisable () {
  151. if (clearStateOnDisable)
  152. ClearState();
  153. }
  154. public void ClearState () {
  155. if (colliderTable != null)
  156. foreach (var col in colliderTable.Values)
  157. col.enabled = false;
  158. currentAttachment = null;
  159. currentAttachmentName = null;
  160. currentCollider = null;
  161. }
  162. void DisposeExcessCollidersAfter (int requiredCount) {
  163. var colliders = GetComponents<PolygonCollider2D>();
  164. if (colliders.Length == 0) return;
  165. for (int i = requiredCount; i < colliders.Length; ++i) {
  166. var collider = colliders[i];
  167. if (collider != null) {
  168. #if UNITY_EDITOR
  169. if (Application.isEditor && !Application.isPlaying)
  170. DestroyImmediate(collider);
  171. else
  172. #endif
  173. Destroy(collider);
  174. }
  175. }
  176. }
  177. void LateUpdate () {
  178. if (slot != null && slot.Attachment != currentAttachment)
  179. MatchAttachment(slot.Attachment);
  180. }
  181. /// <summary>Sets the current collider to match attachment.</summary>
  182. /// <param name="attachment">If the attachment is not a bounding box, it will be treated as null.</param>
  183. void MatchAttachment (Attachment attachment) {
  184. var bbAttachment = attachment as BoundingBoxAttachment;
  185. if (BoundingBoxFollower.DebugMessages && attachment != null && bbAttachment == null)
  186. Debug.LogWarning("BoundingBoxFollower tried to match a non-boundingbox attachment. It will treat it as null.");
  187. if (currentCollider != null)
  188. currentCollider.enabled = false;
  189. if (bbAttachment == null) {
  190. currentCollider = null;
  191. currentAttachment = null;
  192. currentAttachmentName = null;
  193. } else {
  194. PolygonCollider2D foundCollider;
  195. colliderTable.TryGetValue(bbAttachment, out foundCollider);
  196. if (foundCollider != null) {
  197. currentCollider = foundCollider;
  198. currentCollider.enabled = true;
  199. currentAttachment = bbAttachment;
  200. currentAttachmentName = nameTable[bbAttachment];
  201. } else {
  202. currentCollider = null;
  203. currentAttachment = bbAttachment;
  204. currentAttachmentName = null;
  205. if (BoundingBoxFollower.DebugMessages) Debug.LogFormat("Collider for BoundingBoxAttachment named '{0}' was not initialized. It is possibly from a new skin. currentAttachmentName will be null. You may need to call BoundingBoxFollower.Initialize(overwrite: true);", bbAttachment.Name);
  206. }
  207. }
  208. }
  209. }
  210. }