MixAndMatch.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. using Spine.Unity.AttachmentTools;
  30. using System.Collections;
  31. using UnityEngine;
  32. namespace Spine.Unity.Examples {
  33. // This is an example script that shows you how to change images on your skeleton using UnityEngine.Sprites.
  34. public class MixAndMatch : MonoBehaviour {
  35. #region Inspector
  36. [SpineSkin]
  37. public string templateAttachmentsSkin = "base";
  38. public Material sourceMaterial; // This will be used as the basis for shader and material property settings.
  39. [Header("Visor")]
  40. public Sprite visorSprite;
  41. [SpineSlot] public string visorSlot;
  42. [SpineAttachment(slotField: "visorSlot", skinField: "baseSkinName")] public string visorKey = "goggles";
  43. [Header("Gun")]
  44. public Sprite gunSprite;
  45. [SpineSlot] public string gunSlot;
  46. [SpineAttachment(slotField: "gunSlot", skinField: "baseSkinName")] public string gunKey = "gun";
  47. [Header("Runtime Repack")]
  48. public bool repack = true;
  49. public BoundingBoxFollower bbFollower;
  50. [Header("Do not assign")]
  51. public Texture2D runtimeAtlas;
  52. public Material runtimeMaterial;
  53. #endregion
  54. Skin customSkin;
  55. void OnValidate () {
  56. if (sourceMaterial == null) {
  57. var skeletonAnimation = GetComponent<SkeletonAnimation>();
  58. if (skeletonAnimation != null)
  59. sourceMaterial = skeletonAnimation.SkeletonDataAsset.atlasAssets[0].PrimaryMaterial;
  60. }
  61. }
  62. IEnumerator Start () {
  63. yield return new WaitForSeconds(1f); // Delay for one second before applying. For testing.
  64. Apply();
  65. }
  66. void Apply () {
  67. var skeletonAnimation = GetComponent<SkeletonAnimation>();
  68. var skeleton = skeletonAnimation.Skeleton;
  69. // STEP 0: PREPARE SKINS
  70. // Let's prepare a new skin to be our custom skin with equips/customizations. We get a clone so our original skins are unaffected.
  71. customSkin = customSkin ?? new Skin("custom skin"); // This requires that all customizations are done with skin placeholders defined in Spine.
  72. var templateSkin = skeleton.Data.FindSkin(templateAttachmentsSkin);
  73. // STEP 1: "EQUIP" ITEMS USING SPRITES
  74. // STEP 1.1 Find the original/template attachment.
  75. // Step 1.2 Get a clone of the original/template attachment.
  76. // Step 1.3 Apply the Sprite image to the clone.
  77. // Step 1.4 Add the remapped clone to the new custom skin.
  78. // Let's do this for the visor.
  79. int visorSlotIndex = skeleton.Data.FindSlot(visorSlot).Index; // You can access GetAttachment and SetAttachment via string, but caching the slotIndex is faster.
  80. Attachment templateAttachment = templateSkin.GetAttachment(visorSlotIndex, visorKey); // STEP 1.1
  81. // Note: Each call to `GetRemappedClone()` with parameter `premultiplyAlpha` set to `true` creates
  82. // a cached Texture copy which can be cleared by calling AtlasUtilities.ClearCache() as done in the method below.
  83. Attachment newAttachment = templateAttachment.GetRemappedClone(visorSprite, sourceMaterial, pivotShiftsMeshUVCoords: false); // STEP 1.2 - 1.3
  84. customSkin.SetAttachment(visorSlotIndex, visorKey, newAttachment); // STEP 1.4
  85. // And now for the gun.
  86. int gunSlotIndex = skeleton.Data.FindSlot(gunSlot).Index;
  87. Attachment templateGun = templateSkin.GetAttachment(gunSlotIndex, gunKey); // STEP 1.1
  88. Attachment newGun = templateGun.GetRemappedClone(gunSprite, sourceMaterial, pivotShiftsMeshUVCoords: false); // STEP 1.2 - 1.3
  89. if (newGun != null) customSkin.SetAttachment(gunSlotIndex, gunKey, newGun); // STEP 1.4
  90. // customSkin.RemoveAttachment(gunSlotIndex, gunKey); // To remove an item.
  91. // customSkin.Clear()
  92. // Use skin.Clear() To remove all customizations.
  93. // Customizations will fall back to the value in the default skin if it was defined there.
  94. // To prevent fallback from happening, make sure the key is not defined in the default skin.
  95. // STEP 3: APPLY AND CLEAN UP.
  96. // Recommended, preferably at level-load-time: REPACK THE CUSTOM SKIN TO MINIMIZE DRAW CALLS
  97. // IMPORTANT NOTE: the GetRepackedSkin() operation is expensive - if multiple characters
  98. // need to call it every few seconds the overhead will outweigh the draw call benefits.
  99. //
  100. // Repacking requires that you set all source textures/sprites/atlases to be Read/Write enabled in the inspector.
  101. // Combine all the attachment sources into one skin. Usually this means the default skin and the custom skin.
  102. // call Skin.GetRepackedSkin to get a cloned skin with cloned attachments that all use one texture.
  103. if (repack) {
  104. var repackedSkin = new Skin("repacked skin");
  105. repackedSkin.AddSkin(skeleton.Data.DefaultSkin); // Include the "default" skin. (everything outside of skin placeholders)
  106. repackedSkin.AddSkin(customSkin); // Include your new custom skin.
  107. // Note: materials and textures returned by GetRepackedSkin() behave like 'new Texture2D()' and need to be destroyed
  108. if (runtimeMaterial)
  109. Destroy(runtimeMaterial);
  110. if (runtimeAtlas)
  111. Destroy(runtimeAtlas);
  112. repackedSkin = repackedSkin.GetRepackedSkin("repacked skin", sourceMaterial, out runtimeMaterial, out runtimeAtlas); // Pack all the items in the skin.
  113. skeleton.SetSkin(repackedSkin); // Assign the repacked skin to your Skeleton.
  114. if (bbFollower != null) bbFollower.Initialize(true);
  115. } else {
  116. skeleton.SetSkin(customSkin); // Just use the custom skin directly.
  117. }
  118. skeleton.SetSlotsToSetupPose(); // Use the pose from setup pose.
  119. skeletonAnimation.Update(0); // Use the pose in the currently active animation.
  120. // `GetRepackedSkin()` and each call to `GetRemappedClone()` with parameter `premultiplyAlpha` set to `true`
  121. // cache necessarily created Texture copies which can be cleared by calling AtlasUtilities.ClearCache().
  122. // You can optionally clear the textures cache after multiple repack operations.
  123. // Just be aware that while this cleanup frees up memory, it is also a costly operation
  124. // and will likely cause a spike in the framerate.
  125. AtlasUtilities.ClearCache();
  126. Resources.UnloadUnusedAssets();
  127. }
  128. }
  129. }