暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SpriteResolver.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. using System;
  2. using UnityEngine.Animations;
  3. using UnityEngine.Scripting.APIUpdating;
  4. using UnityEngine.U2D.Common;
  5. namespace UnityEngine.U2D.Animation
  6. {
  7. /// <summary>
  8. /// Updates a SpriteRenderer's Sprite reference on the Category and Label value it is set.
  9. /// </summary>
  10. /// <Description>
  11. /// By setting the SpriteResolver's Category and Label value, it will request for a Sprite from
  12. /// a SpriteLibrary Component the Sprite that is registered for the Category and Label.
  13. /// If a SpriteRenderer is present in the same GameObject, the SpriteResolver will update the
  14. /// SpriteRenderer's Sprite reference to the corresponding Sprite.
  15. /// </Description>
  16. [ExecuteInEditMode]
  17. [DisallowMultipleComponent]
  18. [AddComponentMenu("2D Animation/Sprite Resolver")]
  19. [IconAttribute(IconUtility.IconPath + "Animation.SpriteResolver.png")]
  20. [DefaultExecutionOrder(-2)]
  21. [HelpURL("https://docs.unity3d.com/Packages/com.unity.2d.animation@9.0/manual/SL-Resolver.html")]
  22. [MovedFrom("UnityEngine.Experimental.U2D.Animation")]
  23. public class SpriteResolver : MonoBehaviour, ISerializationCallbackReceiver, IPreviewable
  24. {
  25. // SpriteHash is the new animation key.
  26. // We are keeping the old ones so that the animation clip doesn't break
  27. // These are for animation
  28. [SerializeField]
  29. float m_CategoryHash = 0;
  30. [SerializeField]
  31. float m_labelHash = 0;
  32. [SerializeField]
  33. float m_SpriteKey = 0;
  34. [SerializeField, DiscreteEvaluation]
  35. int m_SpriteHash = 0;
  36. // For comparing hash values
  37. int m_CategoryHashInt;
  38. int m_LabelHashInt;
  39. // For OnUpdate during animation playback
  40. int m_PreviousCategoryHash;
  41. int m_PreviousLabelHash;
  42. int m_PreviousSpriteKeyInt;
  43. int m_PreviousSpriteHash;
  44. #if UNITY_EDITOR
  45. bool m_SpriteLibChanged;
  46. /// <summary>
  47. /// Raised when object is deserialized in the Editor.
  48. /// </summary>
  49. public event Action onDeserializedCallback = () => { };
  50. #endif
  51. void Reset()
  52. {
  53. // If the Sprite referred to by the SpriteRenderer exist in the library,
  54. // we select the Sprite
  55. if(spriteRenderer)
  56. SetSprite(spriteRenderer.sprite);
  57. }
  58. void SetSprite(Sprite sprite)
  59. {
  60. var sl = spriteLibrary;
  61. if (sl != null && sprite != null)
  62. {
  63. foreach (var cat in sl.categoryNames)
  64. {
  65. var entries = sl.GetEntryNames(cat);
  66. foreach (var ent in entries)
  67. {
  68. if (sl.GetSprite(cat, ent) == sprite)
  69. {
  70. m_SpriteHash = SpriteLibrary.GetHashForCategoryAndEntry(cat, ent);
  71. return;
  72. }
  73. }
  74. }
  75. }
  76. }
  77. void OnEnable()
  78. {
  79. InitializeSerializedData();
  80. ResolveSpriteToSpriteRenderer();
  81. }
  82. void InitializeSerializedData()
  83. {
  84. m_CategoryHashInt = InternalEngineBridge.ConvertFloatToInt(m_CategoryHash);
  85. m_LabelHashInt = InternalEngineBridge.ConvertFloatToInt(m_labelHash);
  86. m_PreviousSpriteKeyInt = SpriteLibraryUtility.Convert32BitTo30BitHash(InternalEngineBridge.ConvertFloatToInt(m_SpriteKey));
  87. m_SpriteKey = InternalEngineBridge.ConvertIntToFloat(m_PreviousSpriteKeyInt);
  88. if (m_SpriteHash == 0)
  89. {
  90. if (m_SpriteKey != 0f)
  91. m_SpriteHash = InternalEngineBridge.ConvertFloatToInt(m_SpriteKey);
  92. else
  93. m_SpriteHash = ConvertCategoryLabelHashToSpriteKey(spriteLibrary, SpriteLibraryUtility.Convert32BitTo30BitHash(m_CategoryHashInt), SpriteLibraryUtility.Convert32BitTo30BitHash(m_LabelHashInt));
  94. }
  95. m_PreviousSpriteHash = m_SpriteHash;
  96. string newCat, newLab;
  97. if (spriteLibrary != null && spriteLibrary.GetCategoryAndEntryNameFromHash(m_SpriteHash, out newCat, out newLab))
  98. {
  99. // Populate back in case user is using animating with old animation clip
  100. m_CategoryHashInt = SpriteLibraryUtility.GetStringHash(newCat);
  101. m_LabelHashInt = SpriteLibraryUtility.GetStringHash(newLab);
  102. m_CategoryHash = InternalEngineBridge.ConvertIntToFloat(m_CategoryHashInt);
  103. m_labelHash = InternalEngineBridge.ConvertIntToFloat(m_LabelHashInt);
  104. }
  105. m_PreviousLabelHash = m_LabelHashInt;
  106. m_PreviousCategoryHash = m_CategoryHashInt;
  107. }
  108. SpriteRenderer spriteRenderer => GetComponent<SpriteRenderer>();
  109. /// <summary>
  110. /// Set the Category and label to use.
  111. /// </summary>
  112. /// <param name="category">Category to use.</param>
  113. /// <param name="label">Label to use.</param>
  114. /// <returns>True if the Category and Label were successfully set.</returns>
  115. public bool SetCategoryAndLabel(string category, string label)
  116. {
  117. m_SpriteHash = SpriteLibrary.GetHashForCategoryAndEntry(category, label);
  118. m_PreviousSpriteHash = m_SpriteHash;
  119. return ResolveSpriteToSpriteRenderer();
  120. }
  121. /// <summary>
  122. /// Get the Category set for the SpriteResolver.
  123. /// </summary>
  124. /// <returns>The Category's name.</returns>
  125. public string GetCategory()
  126. {
  127. var returnString = "";
  128. var sl = spriteLibrary;
  129. if (sl)
  130. {
  131. sl.GetCategoryAndEntryNameFromHash(m_SpriteHash, out returnString, out _);
  132. }
  133. return returnString;
  134. }
  135. /// <summary>
  136. /// Get the Label set for the SpriteResolver.
  137. /// </summary>
  138. /// <returns>The Label's name.</returns>
  139. public string GetLabel()
  140. {
  141. var returnString = "";
  142. var sl = spriteLibrary;
  143. if (sl)
  144. sl.GetCategoryAndEntryNameFromHash(m_SpriteHash, out _, out returnString);
  145. return returnString;
  146. }
  147. /// <summary>
  148. /// Property to get the SpriteLibrary the SpriteResolver is resolving from.
  149. /// </summary>
  150. public SpriteLibrary spriteLibrary => gameObject.GetComponentInParent<SpriteLibrary>(true);
  151. /// <summary>
  152. /// Empty method. Implemented for the IPreviewable interface.
  153. /// </summary>
  154. public void OnPreviewUpdate() { }
  155. #if UNITY_EDITOR
  156. void OnDidApplyAnimationProperties()
  157. {
  158. if(IsInGUIUpdateLoop())
  159. ResolveUpdatedValue();
  160. }
  161. #endif
  162. static bool IsInGUIUpdateLoop() => Event.current != null;
  163. void LateUpdate()
  164. {
  165. ResolveUpdatedValue();
  166. }
  167. void ResolveUpdatedValue()
  168. {
  169. if (m_SpriteHash != m_PreviousSpriteHash)
  170. {
  171. m_PreviousSpriteHash = m_SpriteHash;
  172. ResolveSpriteToSpriteRenderer();
  173. }
  174. else
  175. {
  176. var spriteKeyInt = InternalEngineBridge.ConvertFloatToInt(m_SpriteKey);
  177. if (spriteKeyInt != m_PreviousSpriteKeyInt)
  178. {
  179. m_SpriteHash = SpriteLibraryUtility.Convert32BitTo30BitHash(spriteKeyInt);
  180. m_PreviousSpriteKeyInt = spriteKeyInt;
  181. ResolveSpriteToSpriteRenderer();
  182. }
  183. else
  184. {
  185. m_CategoryHashInt = InternalEngineBridge.ConvertFloatToInt(m_CategoryHash);
  186. m_LabelHashInt = InternalEngineBridge.ConvertFloatToInt(m_labelHash);
  187. if (m_LabelHashInt != m_PreviousLabelHash || m_CategoryHashInt != m_PreviousCategoryHash)
  188. {
  189. if (spriteLibrary != null)
  190. {
  191. m_PreviousCategoryHash = m_CategoryHashInt;
  192. m_PreviousLabelHash = m_LabelHashInt;
  193. m_SpriteHash = ConvertCategoryLabelHashToSpriteKey(spriteLibrary, SpriteLibraryUtility.Convert32BitTo30BitHash(m_CategoryHashInt), SpriteLibraryUtility.Convert32BitTo30BitHash(m_LabelHashInt));
  194. m_PreviousSpriteHash = m_SpriteHash;
  195. ResolveSpriteToSpriteRenderer();
  196. }
  197. }
  198. }
  199. }
  200. }
  201. internal static int ConvertCategoryLabelHashToSpriteKey(SpriteLibrary library, int categoryHash, int labelHash)
  202. {
  203. if (library != null)
  204. {
  205. foreach(var category in library.categoryNames)
  206. {
  207. if (categoryHash == SpriteLibraryUtility.GetStringHash(category))
  208. {
  209. var entries = library.GetEntryNames(category);
  210. if (entries != null)
  211. {
  212. foreach (var entry in entries)
  213. {
  214. if (labelHash == SpriteLibraryUtility.GetStringHash(entry))
  215. {
  216. return SpriteLibrary.GetHashForCategoryAndEntry(category, entry);
  217. }
  218. }
  219. }
  220. }
  221. }
  222. }
  223. return 0;
  224. }
  225. internal Sprite GetSprite(out bool validEntry)
  226. {
  227. var lib = spriteLibrary;
  228. if (lib != null)
  229. {
  230. return lib.GetSpriteFromCategoryAndEntryHash(m_SpriteHash, out validEntry);
  231. }
  232. validEntry = false;
  233. return null;
  234. }
  235. /// <summary>
  236. /// Set the Sprite in SpriteResolver to the SpriteRenderer component that is in the same GameObject.
  237. /// </summary>
  238. /// <returns>True if it successfully resolved the Sprite.</returns>
  239. public bool ResolveSpriteToSpriteRenderer()
  240. {
  241. m_PreviousSpriteHash = m_SpriteHash;
  242. var sprite = GetSprite(out var validEntry);
  243. var sr = spriteRenderer;
  244. if (sr != null && (sprite != null || validEntry))
  245. sr.sprite = sprite;
  246. return validEntry;
  247. }
  248. void OnTransformParentChanged()
  249. {
  250. ResolveSpriteToSpriteRenderer();
  251. #if UNITY_EDITOR
  252. spriteLibChanged = true;
  253. #endif
  254. }
  255. #if UNITY_EDITOR
  256. internal bool spriteLibChanged
  257. {
  258. get => m_SpriteLibChanged;
  259. set => m_SpriteLibChanged = value;
  260. }
  261. #endif
  262. /// <summary>
  263. /// Called before object is serialized.
  264. /// </summary>
  265. void ISerializationCallbackReceiver.OnBeforeSerialize()
  266. {
  267. }
  268. /// <summary>
  269. /// Called after object is deserialized.
  270. /// </summary>
  271. void ISerializationCallbackReceiver.OnAfterDeserialize()
  272. {
  273. #if UNITY_EDITOR
  274. onDeserializedCallback();
  275. #endif
  276. }
  277. }
  278. }