Licensing

A Spine license is required to integrate the Spine Runtimes into your applications.

spine-unity Runtime Documentation

Main Components

The spine-unity runtime provides you with a set of components that allow to display, animate, follow and modify skeletons exported from Spine. These components reference skeleton data and texture atlas assets you import as described in the Assets section.

Adding a Skeleton to a Scene

To quickly display a Spine skeleton in your Unity project:

  1. Import the skeleton data and texture atlas as described in the Assets section.
  2. Drag the _SkeletonData asset into the Scene view or the Hierarchy panel and choose SkeletonAnimation. A new GameObject will be instantiated, with the required Spine components already set up.

Note: Alternatively to step 2, you can create the same GameObject from scratch:

  1. Create a new empty GameObject via GameObject -> Create Empty.
  2. Select the GameObject and in the inspector click Add Component, then select SkeletonAnimation. This will automatically add the additional MeshRenderer and MeshFilter components as well.
  3. At the SkeletonAnimation component, assign the Skeleton Data Asset property by dragging the desired _SkeletonData asset into it.

Note: In case you only see bones of a skeleton in Scene view without any images attached, you might want to switch the Initial Skin property to a skin other than default.

You can now use the components' C# API to animate the skeleton, react to events triggered by animations, etc. Refer to the component documentation below for more details.

Alternatives to SkeletonAnimation - SkeletonGraphic (UI) and SkeletonMecanim

Instantiating a skeleton as SkeletonAnimation is the recommended way to use a Spine skeleton in Unity, as it provides the most complete feature set of the three alternatives.

The three alternatives to instantiate a skeleton are:

  1. SkeletonAnimation - Uses Spine's custom animation and event system, providing highest customizability. Renders using a MeshRenderer, interacting with masks such as SpriteMask like a Unity sprite. The recommended way of using a Spine skeleton in Unity.
  2. SkeletonGraphic (UI) - For use as UI element together with a Unity Canvas. Renders and interacts with UI masks such as RectMask2D like the built-in Unity UI elements. Animation and event behavior is identical to SkeletonAnimation.
  3. SkeletonMecanim - Uses Unity's Mecanim animation and event system for starting, mixing and transitioning between animations. Provides fewer animation mixing and transition options than SkeletonAnimation. When using SkeletonMecanim it will not be guaranteed that transitions will look as previewed in the Spine Editor.

Advanced - Instantiation at Runtime

Note: Prefer using the normal workflow of adding a skeleton to a scene and storing them in a prefabs or reusing pooled objects from an instance pool for instantiation. This makes customization and adjustments easier.

While it's not the recommended workflow, the spine-unity API allows you to instantiate SkeletonAnimation and SkeletonGraphic GameObjects at runtime from a SkeletonDataAsset, or even directly from the three exported assets. Instantiation directly from the exported assets is only recommended if you can't use the normal Unity import pipeline to automatically create SkeletonDataAsset and SpineAtlasAsset assets beforehand.

C#
// instantiating a SkeletonAnimation GameObject from a SkeletonDataAsset
SkeletonAnimation instance = SkeletonAnimation.NewSkeletonAnimationGameObject(skeletonDataAsset);

// instantiating a SkeletonGraphic GameObject from a SkeletonDataAsset
SkeletonGraphic instance
   = SkeletonGraphic.NewSkeletonGraphicGameObject(skeletonDataAsset, transform, skeletonGraphicMaterial);
C#
// instantiation from exported assets without prior import
// 1. Create the AtlasAsset (needs atlas text asset and textures, and materials/shader);
// 2. Create SkeletonDataAsset (needs json or binary asset file, and an AtlasAsset)
SpineAtlasAsset runtimeAtlasAsset
   = SpineAtlasAsset.CreateRuntimeInstance(atlasTxt, textures, materialPropertySource, true);
SkeletonDataAsset runtimeSkeletonDataAsset
   = SkeletonDataAsset.CreateRuntimeInstance(skeletonJson, runtimeAtlasAsset, true);
// 3. Create SkeletonAnimation (needs a valid SkeletonDataAsset)
SkeletonAnimation instance = SkeletonAnimation.NewSkeletonAnimationGameObject(runtimeSkeletonDataAsset);

You can examine the example scene Spine Examples/Other Examples/Instantiate from Script and the used example scripts SpawnFromSkeletonDataExample.cs, RuntimeLoadFromExportsExample.cs and SpawnSkeletonGraphicExample.cs for additional information.

SkeletonAnimation Component

The SkeletonAnimation component is one of three ways to use a Spine skeleton in Unity. These alternatives are: SkeletonAnimation, SkeletonMecanim and SkeletonGraphic (UI).

The SkeletonAnimation component is the heart of the spine-unity runtime. It allows you to add a Spine skeleton to a GameObject, animate it, react to animation events, and so on.

Setting Skeleton Data

A SkeletonAnimation component requires a reference to a skeleton data asset from which it can get the information about a skeleton's bone hierarchy, slots etc.

If you have added a skeleton to a scene via drag and drop, the skeleton data asset is automatically assigned. In case you have an already set up GameObject and suddenly want to change the skeleton to a different asset, you can manually change it via the provided Inspector property.

To set or change the skeleton data

  1. Select the SkeletonAnimation GameObject
  2. Assign a _SkeletonData asset at the SkeletonData Asset property in the Inspector.

Setting Initial Skin and Animation

The SkeletonAnimation Inspector exposes the following parameters

  1. Initial Skin. This skin will be assigned upon start. Note: In case you only see bones of a skeleton without any images attached, you might want to switch to a skin other than default to show your skin.
  2. Animation Name. This animation will be played upon start.
  3. Loop. Defines whether the initial animation shall be looped or played only once.
  4. Time Scale. You can set the time scale to slow down or speed up playback of animations.
  5. Unscaled Time. When set to true, updates will be performed according to Time.unscaledDeltaTime instead of Time.deltaTime. This is useful to animate UI elements independently of slow-motion effects.

Enabling Root Motion

Root motion for SkeletonAnimation and SkeletonGraphic (UI) components is provided via a separate SkeletonRootMotion component. The SkeletonAnimation Inspector provides a Root Motion Add Component button to quickly add the suitable component to your skeleton GameObject.

Setting Advanced Parameters

Unfold the Advanced section in the SkeletonAnimation Inspector to show advanced configuration parameters.

The SkeletonAnimation Inspector exposes the following advanced parameters

  • Initial Flip X, Initial Flip Y. These parameters allow you to flip the skeleton horizontally and vertically upon start. This will set ScaleX and ScaleY to -1 where flipped.
  • Animation Update. Whether to update the animation in normal Update (the default), physics step FixedUpdate, or manually via a user call. When using a SkeletonRootMotion component with a Rigidbody or Rigidbody2D assigned, it is recommended to set the update mode to In FixedUpdate. Otherwise In Update is recommended.
  • Update When Invisible. Update mode used when the MeshRenderer becomes invisible. Update mode is automatically reset to UpdateMode.FullUpdate when the mesh becomes visible again.
  • Use single submesh. Can be enabled to simplify submesh generation by assuming you are only using one Material and need only one submesh. This is will disable multiple materials, render separation, and custom slot materials.
  • Fix Draw Order. Applies only when 3+ submeshes are used (2+ materials with alternating order, e.g. "A B A"). If true, MaterialPropertyBlocks are assigned at each material to prevent aggressive batching of submeshes by e.g. the LWRP renderer, leading to incorrect draw order (e.g. "A1 B A2" changed to "A1A2 B"). You can leave this parameter disabled when everything is drawn correctly to save the additional performance cost.
  • Immutable triangles. Can be enabled to optimize rendering for skeletons that never change attachment visbility. If true, triangles will not be updated. Enable this as an optimization if the skeleton does not make use of attachment swapping or hiding, or draw order keys. Otherwise, setting this to false may cause errors in rendering.
  • Clear State on Disable. Clears the state of the render and skeleton when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful.
  • Fix Prefab Override MeshFilter. Fixes the prefab always being marked as changed (sets the MeshFilter's hide flags to DontSaveInEditor), but at the cost of references to the MeshFilter by other components being lost. When set to Use Global Settings, the setting in Spine Preferences is used.
  • Separator Slot Names. Slots that determine where the render is split. This is used by components such as SkeletonRenderSeparator so that the skeleton can be rendered by two separate renderers on different GameObjects.
  • Z-Spacing. Attachments are rendered back to front in the x/y plane by the skeleton renderer component. Each attachment is offset by a customizable z-spacing value on the z-axis to avoid z-fighting.

  • PMA Vertex Colors. Multiply vertex color RGB with vertex color alpha. Enable this parameter if the shader used for rendering is a Spine shader (even with Straight Alpha Texture) or a thirdparty shader which uses PMA additive blend mode Blend One OneMinusSrcAlpha. Disable this parameter for normal shaders with regular blend mode Blend SrcAlpha OneMinusSrcAlpha. When enabled, additive slots can be rendered in a single draw call together with normal slots. When disabled, additive slots require SkeletonData Blend Mode Materials - Apply Additive Material enabled, leading to a separate draw call, which may adversely affect performance.
  • Tint Black (!). Adds black tint vertex data to the mesh. Enable if the skeleton has any slots with tint black color set.
    Black tinting requires that the shader interprets UV2 and UV3 as black tint colors for this effect to work. You may use the included Spine/Skeleton Tint Black shader. If you only need to tint the whole skeleton and not individual parts, the Spine/Skeleton Tint shader is recommended for better efficiency and changing/animating the _Black material property via MaterialPropertyBlock. See section Shaders for additional information. To retain batching while tinting multiple skeletons differently, tinting via Skeleton.R .G .B .A is recommended.
  • Add Normals. When enabled, the mesh generator adds normals to the output mesh. Enable if your shader requires vertex normals. For better performance and reduced memory usage, you can instead use a shader such as the Spine/Skeleton Lit shader that assumes the desired normal. Note that the Spine/Sprite shaders can be configured to assume a Fixed Normal as well.
  • Solve Tangents. Some lit shaders require vertex tangents, usually for applying normal maps. When enabled, tangents are calculated every frame and added to the output mesh.
  • Physics Inheritance. Controls how Transform movement is applied to PhysicsConstraints of the skeleton.
    • Position. When set to non-zero, Transform position movement in X and Y direction is applied to skeleton PhysicsConstraints, multiplied by these X and Y scale factors. Typical (X,Y) values are:
      (1,1) to apply XY movement normally,
      (2,2) to apply movement with double intensity,
      (1,0) to apply only horizontal movement, or
      (0,0) to not apply any Transform position movement at all.
    • Rotation. When set to non-zero, Transform rotation movement is applied to skeleton PhysicsConstraints, multiplied by this scale factor. Typical values are:
      1 to apply movement normally,
      2 to apply movement with double intensity, or
      0 to not apply any Transform rotation movement at all.
    • Movement relative to. To apply Transform movement relative to e.g. a parent Transform, set this to the reference Transform relative to which movement shall be calculated. Set this to None to use the absolute world location (the default).
  • Add Skeleton Utility. This button can be used to quickly add a SkeletonUtility component to the GameObject for tracking or overriding bone positions. See SkeletonUtility for further info.
  • Debug. Sometimes you may want to know the current color of a slot or scale of a bone while the game is running. Pressing the Debug button opens the Skeleton Debug window which was created for this purpose. It allows you to inspect the current state of bones, slots, constraints, draw order, events and statistical information about your skeleton.

Life-cycle


In the SkeletonAnimation component, AnimationState holds the state of all currently playing and queued animations. Every Update, the AnimationState is updated so that the animations progress forward in time. Then the new frame is applied to the Skeleton as a new pose.

C#

Interacting with a skeleton via code requires accessing the SkeletonAnimation component. As applies to Unity components in general, it is recommended to query the reference once and store it for further use.

C#
...
using Spine.Unity;

public class YourComponent : MonoBehaviour {

   SkeletonAnimation skeletonAnimation;
   Spine.AnimationState animationState;
   Spine.Skeleton skeleton;

   void Awake () {
      skeletonAnimation = GetComponent<SkeletonAnimation>();
      skeleton = skeletonAnimation.Skeleton;
      //skeletonAnimation.Initialize(false); // when not accessing skeletonAnimation.Skeleton,
                                 // use Initialize(false) to ensure everything is loaded.
      animationState = skeletonAnimation.AnimationState;
   }

Your scripts may run before or after SkeletonAnimation's Update. If your code takes Skeleton or bone values before SkeletonAnimation's Update, your code will read values from the previous frame instead of the current one.

The component exposes the event callback delegates as properties that allow you to intercept this life-cycle before and after the world transforms of all bones are calculated. You can bind to these delegates to modify bone positions and other aspects of the skeleton without having to care for the update order of your actors and components.

SkeletonAnimation Update Callbacks

  • SkeletonAnimation.BeforeApply is raised before the animations for the frame are applied. Use this callback when you want to change the skeleton state before animations are applied on top.
  • SkeletonAnimation.UpdateLocal is raised after the animations for the frame are updated and applied to the skeleton's local values. Use this if you need to read or modify bone local values.
  • SkeletonAnimation.UpdateComplete is raised after world values are calculated for all bones in the Skeleton. SkeletonAnimation makes no further operations in Update after this. Use this if you only need to read bone world values. Those values may still change if any of your scripts modify them after SkeletonAnimation's Update.
  • SkeletonAnimation.UpdateWorld is raised after the world values are calculated for all the bones in the Skeleton. If you subscribe to this event, it will call skeleton.UpdateWorldTransform a second time. Depending on the complexity of your skeleton or what you are doing, this may be unnecessary, or wasteful. Use this event if you need to modify bone local values based on bone world values. This is useful for implementing custom constraints in Unity code.

C#
// your delegate method
void AfterUpdateComplete (ISkeletonAnimation anim) {
   // this is called after animation updates have been completed.
}

// register your delegate method
void Start() {
   skeletonAnimation.UpdateComplete -= AfterUpdateComplete;
   skeletonAnimation.UpdateComplete += AfterUpdateComplete;
}

SkeletonRenderer Update Callbacks

  • OnRebuild is raised after the Skeleton is successfully initialized.
  • OnMeshAndMaterialsUpdated is raised at the end of LateUpdate() after the Mesh and all materials have been updated.

C#
// your delegate method for OnMeshAndMaterialsUpdated
void AfterMeshAndMaterialsUpdated (SkeletonRenderer renderer) {
   // this is called after mesh and materials have been updated.
}

// your delegate method for OnRebuild
void AfterRebuild (SkeletonRenderer renderer) {
   // this is called after the Skeleton is successfully initialized.
}

// register your delegate method
void Start() {
   skeletonAnimation.OnMeshAndMaterialsUpdated -= AfterMeshAndMaterialsUpdated;
   skeletonAnimation.OnMeshAndMaterialsUpdated += AfterMeshAndMaterialsUpdated;

   skeletonAnimation.OnRebuild -= AfterRebuild;
   skeletonAnimation.OnRebuild += AfterRebuild;
}

As an alternative, you can change Script Execution Order to run after SkeletonAnimation's Update method.

Script Execution Order

In Unity, each component's Update and LateUpdate calls are ordered according to script execution order (see ExecutionOrder and DefaultExecutionOrder for details). When issuing calls from your own component's Update or LateUpdate methods that modify skeleton or animation state, it is important to execute at the right time relative to the SkeletonAnimation component.

The update sequence of SkeletonAnimation is as follows:

  • SkeletonAnimation.Update: Updates animations, applies animations to the skeleton.
  • SkeletonAnimation.LateUpdate: Updates the skeleton mesh based on skeleton state.

To modify skeleton state:

  • To run before animations are applied, issue the call from Update and set execution order to before SkeletonAnimation.
  • To run after animations are applied and before the skeleton mesh is generated, issue the call from Update and set execution order to after SkeletonAnimation. Alternatively issue the call from LateUpdate and set execution order to before SkeletonAnimation.

C#
// At execution order -1, this component executes before SkeletonAnimation and SkeletonRenderer.
[DefaultExecutionOrder(-1)]
public class SetupPoseComponent : MonoBehaviour {
   ...

   void Update() {
      // This call lets the skeleton start from setup-pose each frame before applying animations.
      // SetupPoseComponent.Update needs to be called before SkeletonAnimation.Update, which is ensured
      // by [DefaultExecutionOrder(-1)] above.
      skeleton.SetToSetupPose();
   }
}

If you can't change the update order of your script executing too late, you can perform manual updates as described in Manual Updates to still update the skeleton or skeleton mesh within the same frame.

Manual Updates

After certain modifications it may be desired to immediately re-apply animations to your skeleton, or re-generate the skeleton mesh based on the modified skeleton. Compared to the generic runtime, the SkeletonAnimation component provides additional methods allowing consistent updates with a single method call. For example, skeleton.UpdateWorldTransform() is called as part of Update(deltaTime) and ApplyAnimation() listed below.

  • Update(deltaTime) for a full skeleton update. The skeleton mesh remains unchanged.
    SkeletonAnimation.Update(deltaTime) updates the underlying AnimationState, forwards this frame's Transform movement to physics constraints and applies the animations to the skeleton, followed by updating all bone's world transforms. This may be necessary when you need to perform a full skeleton update without advancing time, or if you want to advance by a custom delta-time.

C#
// After setting bones and slots to setup pose, perform a full skeleton update without advancing time.
skeleton.SetToSetupPose();
skeletonAnimation.Update(0);

// Setting only slots to setup pose usually (except for when active skin bones change)
// does not require bone world transform updates, so AnimationState.Apply(skeleton) is sufficient.
skeleton.SetSlotsToSetupPose();
skeletonAnimation.AnimationState.Apply(skeleton)
C#
// If you don't want to advance by Unity Time.deltaTime or unscaledDeltaTime but by a custom delta time.
skeletonAnimation.timeScale = 0f;
...
skeletonAnimation.Update(customDeltaTime);
  • ApplyAnimation() to re-apply animations to the skeleton.
    SkeletonAnimation.ApplyAnimation() similarly re-applies the animations to the skeleton, but without updating the underlying AnimationState or forwarding Transform movement to physics constraints.

  • LateUpdateMesh() to update the skeleton mesh to the skeleton state.
    SkeletonRenderer.LateUpdateMesh() (similar to SkeletonRenderer.LateUpdate() but ignores UpdateMode) updates the skeleton mesh based on the skeleton. This may be necessary when modifying skeleton properties in LateUpdate() and script execution order executes your script too late, after SkeletonAnimation.LateUpdate() has already updated the skeleton mesh for this frame.

C#
// If your script modifies skeleton properties in LateUpdate() and script execution order
// of the script executes after SkeletonAnimation.
void LateUpdate () {
   skeleton.SetToSetupPose(); // perform some skeleton modifications
   skeletonAnimation.Update(0);
   skeletonAnimation.LateUpdateMesh(); // otherwise SkeletonAnimation.LateUpdate would be called next frame
}

Skeleton

The SkeletonAnimation component provides access to the underlying skeleton via the SkeletonAnimation.Skeleton property. A Skeleton stores a reference to a skeleton data asset, which in turn references one or more atlas assets.

The Skeleton allows you to set skins, attachments, reset bones to setup pose and scale and flip the whole skeleton.

Setting Attachments

To set an attachment, provide the slot and attachment name.

C#
bool success = skeletonAnimation.Skeleton.SetAttachment("slotName", "attachmentName");
C#
// using properties
[SpineSlot] public string slotProperty = "slotName";
[SpineAttachment] public string attachmentProperty = "attachmentName";
...
bool success = skeletonAnimation.Skeleton.SetAttachment(slotProperty, attachmentProperty);

Note that [SpineSlot] and [SpineAttachment] in the above code are String Property Attributes described in this section.

Resetting to Setup Pose

For procedural animation it is sometimes necessary to reset bones and/or slots to their setup pose. After setting skins you likely want to call Skeleton.SetSlotsToSetupPose as described in section Setting Skins below.

C#
skeleton.SetToSetupPose();
skeleton.SetBonesToSetupPose();
skeleton.SetSlotsToSetupPose();

Setting Skins

A Spine skeleton may have multiple skins that define which attachment goes on which slot. The skeleton component provides a simple way to switch between skins.

C#
bool success = skeletonAnimation.Skeleton.SetSkin("skinName");
skeletonAnimation.Skeleton.SetSlotsToSetupPose(); // see note below
C#
// using properties
[SpineSkin] public string skinProperty = "skinName";
...
bool success = skeletonAnimation.Skeleton.SetSkin(skinProperty);
skeletonAnimation.Skeleton.SetSlotsToSetupPose(); // see note below

You likely want to call Skeleton.SetSlotsToSetupPose after changing skins if you don't want previously set attachments to affect the visibility of your current attachments. See the documentation here for details.

Combining Skins

Spine skins can be combined to e.g. form a complete character skin from single cloth item skins. See the new Skin API documentation for more details.

C#
var skeleton = skeletonAnimation.Skeleton;
var skeletonData = skeleton.Data;
var mixAndMatchSkin = new Skin("custom-girl");
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("skin-base"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("nose/short"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("eyelids/girly"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("eyes/violet"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("hair/brown"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("clothes/hoodie-orange"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("legs/pants-jeans"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("accessories/bag"));
mixAndMatchSkin.AddSkin(skeletonData.FindSkin("accessories/hat-red-yellow"));
skeleton.SetSkin(mixAndMatchSkin);
skeleton.SetSlotsToSetupPose();
skeletonAnimation.AnimationState.Apply(skeletonAnimation.Skeleton); // skeletonMecanim.Update() for SkeletonMecanim

Runtime Repacking

While combining skins, multiple materials may be accumulated. This leads to additional draw calls. The Skin.GetRepackedSkin() method can be used to combine used texture regions of a collected skin to a single texture at runtime.

C#
using Spine.Unity.AttachmentTools;

// Create a repacked skin.
Skin repackedSkin = collectedSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.SkeletonDataAsset.atlasAssets[0].PrimaryMaterial, out runtimeMaterial, out runtimeAtlas);
collectedSkin.Clear();

// Use the repacked skin.
skeletonAnimation.Skeleton.Skin = repackedSkin;
skeletonAnimation.Skeleton.SetSlotsToSetupPose();
skeletonAnimation.AnimationState.Apply(skeletonAnimation.Skeleton); // skeletonMecanim.Update() for SkeletonMecanim

// You can optionally clear the cache after multiple repack operations.
AtlasUtilities.ClearCache();

Important Note: If repacking fails or creates unexpected results, it is most likely due to any of the following causes:

  1. Read/Write is disabled: Depending on platform capabilities, you may need to set the Read/Write Enabled parameter at source textures that shall be combined to a repacked texture.
  2. Compression is enabled: Depending on the platform, ensure that the source texture has Texture import setting Compression set to None instead of Normal Quality.
  3. Quality tier uses half/quarter resolution textures: There is a known Unity bug that copies incorrect regions when half or quarter resolution rextures are used. Ensure that all Quality tiers in Project Settings are using full resolution textures.
  4. The source texture is not a power-of-two texture but Unity enlarges it to the closest power: Either a) export from Spine with Pack Settings Power of two enabled, or b) make sure the atlas Texture import settings in Unity has Non-Power of Two set to None.

You can examine the example scenes Spine Examples/Other Examples/Mix and Match and Spine Examples/Other Examples/Mix and Match Equip and the used MixAndMatch.cs example script for further insights.

Advanced - Runtime Repacking with Normalmaps

You can also repack normal maps and other additional texture layers alongside the main texture. Pass int[] additionalTexturePropertyIDsToCopy = new int[] { Shader.PropertyToID("_BumpMap") }; as parameter to GetRepackedSkin() to repack both the main texture and the normal map layer.

C#
Material runtimeMaterial;
Texture2D runtimeAtlas;
Texture2D[] additionalOutputTextures = null;
int[] additionalTexturePropertyIDsToCopy = new int[] { Shader.PropertyToID("_BumpMap") };
Skin repackedSkin = prevSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.SkeletonDataAsset.atlasAssets[0].PrimaryMaterial, out runtimeMaterial, out runtimeAtlas,
additionalTexturePropertyIDsToCopy : additionalTexturePropertyIDsToCopy, additionalOutputTextures : additionalOutputTextures);

// Use the repacked skin.
skeletonAnimation.Skeleton.Skin = repackedSkin;
skeletonAnimation.Skeleton.SetSlotsToSetupPose();
skeletonAnimation.AnimationState.Apply(skeletonAnimation.Skeleton); // skeletonMecanim.Update() for SkeletonMecanim

Note: Typically the normal map property is named "_BumpMap". When using a custom shader, be sure to use the respective property name. Note that this name is the property name in the shader, not the "Normal Map" label string shown in the Inspector.

Scaling and Flipping a Skeleton

Flipping a skeleton vertically or horizontally allows you to reuse animations, e.g. a walk animation facing left can be played back to face right.

C#
bool isFlippedX = skeleton.ScaleX < 0;
skeleton.ScaleX = -1;
bool isFlippedY = skeleton.ScaleY < 0;
skeleton.ScaleY = -1;

skeleton.ScaleX = -skeleton.ScaleX; // toggle flip x state

Manually Accessing Bone Transforms

Note: Recommended for very special use cases only. The Spine BoneFollower and Spine SkeletonUtilityBone components are an easier way to interact with bones.

The Skeleton lets you set and get bone transform values so you can implement IK terrain following or let other actors and components such as particle systems follow the bones in your skeleton.

Note: Make sure you get and apply new bone positions as part of the update world transform life-cycle by subscribing to the SkeletonAnimation.UpdateWorld delegate. Otherwise your modifications may be one frame too late when read, or overwritten by animations when set.

C#
Bone bone = skeletonAnimation.Skeleton.FindBone("boneName");
Vector3 worldPosition = bone.GetWorldPosition(skeletonAnimation.transform);
// note: when using SkeletonGraphic, all values need to be scaled by the parent Canvas.referencePixelsPerUnit.

Vector3 position = ...;
bone.SetPositionSkeletonSpace(position);

Quaternion worldRotationQuaternion = bone.GetQuaternion();

Animation - AnimationState

Life-cycle

The SkeletonAnimation component implements the Update method in which it updates the underlying AnimationState based on the delta time, forwards transform movement to skeleton physics, applies the AnimationState to the skeleton, and updates the world transforms of all bones of the skeleton.

The skeleton animation component exposes the AnimationState API via the SkeletonAnimation.AnimationState property. This section assumes a familiarity with concepts like tracks, track entries, mix times, or animation queuing as described in the section Applying Animations in the generic Spine Runtime Guide.

Time Scale

You can set the time scale of the skeleton animation component to slow down or speed up the playback of animations. The delta time used to advance animations is simply multiplied with the time scale, e.g. a time scale of 0.5 slows the animation down to half the normal speed, a time scale of 2 speeds it up to twice the normal speed.

C#
float timeScale = skeletonAnimation.timeScale;
skeletonAnimation.timeScale = 0.5f;

Setting Animations

To set an animation, provide the track index, animation name and whether to loop the animation.

C#
TrackEntry entry = skeletonAnimation.AnimationState.SetAnimation(trackIndex, "walk", true);
C#
// using properties
[SpineAnimation] public string animationProperty = "walk";
...
TrackEntry entry = skeletonAnimation.AnimationState.SetAnimation(trackIndex, animationProperty, true);

As an alternative, you can use an AnimationReferenceAsset instead of a string as parameter.

C#
// using AnimationReferenceAsset
public AnimationReferenceAsset animationReferenceAsset; // assign a generated AnimationReferenceAsset to this property
...
TrackEntry entry = skeletonAnimation.AnimationState.SetAnimation(trackIndex, animationReferenceAsset, true);

Queueing Animations

To queue an animation, provide the track index, animation name, whether to loop the animation, and the delay after which this animation should start playing on the track in seconds.

C#
TrackEntry entry = skeletonAnimation.AnimationState.AddAnimation(trackIndex, "run", true, 2);
C#
// using properties
[SpineAnimation] public string animationProperty = "run";
...
TrackEntry entry = skeletonAnimation.AnimationState.AddAnimation(trackIndex, animationProperty, true, 2);

Empty Animation and Clearing

The skeleton animation component also provides methods to set an empty animation, queue an empty animation, or clear one or all tracks. All of these work analogous to the methods and nodes shown above.

C#
TrackEntry entry = skeletonAnimation.AnimationState.SetEmptyAnimation(trackIndex, mixDuration);
entry = skeletonAnimation.AnimationState.AddEmptyAnimation(trackIndex, mixDuration, delay);
skeletonAnimation.AnimationState.ClearTrack(trackIndex);
skeletonAnimation.AnimationState.ClearTracks();

Track Entries

You'll receive a TrackEntry from all the methods that allows you to further customize the playback of this specific animation, as well as bind to delegates of track entry specific events. See the section Processing AnimationState Events below.

Note: The returned track entries will only be valid until the corresponding animation is removed from the underlying animation state. The Unity garbage collector will automatically free them. After a dispose event is received for a track entry, it should no longer be stored or accessed.

C#
TrackEntry entry = ...
entry.EventThreshold = 2;
float trackEnd = entry.TrackEnd;

Processing AnimationState Events

While animations are played back by the underlying AnimationState, various events will be emitted that notify listeners that

  1. An animation started.
  2. An animation was interrupted, e.g. by clearing a track or setting a new animation.
  3. An animation was completed without interruption, which may occur multiple times if looped.
  4. An animation has ended.
  5. An animation and its corresponding TrackEntry have been disposed.
  6. A user defined event was fired.

Note: When setting a new animation which interrupts a previous one, no complete event will be raised but interrupt and end events will be raised instead.

The skeleton animation component provides delegates to which C# code can bind in order to react to these events for all queued animations on all tracks. Listeners can also be bound to the corresponding delegates of a specific TrackEntry only. So you can register to e.g. AnimationState.Complete to handle event callbacks for any future animation Complete event, or instead register to a single TrackEntry.Complete event to handle Complete events issued by a single specific enqueued animation.

C#

In the class that should react to AnimationState events, add delegates for the events you want to listen to:

C#
SkeletonAnimation skeletonAnimation;
Spine.AnimationState animationState;

void Awake () {
   skeletonAnimation = GetComponent<SkeletonAnimation>();
   animationState = skeletonAnimation.AnimationState;

   // registering for events raised by any animation
   animationState.Start += OnSpineAnimationStart;
   animationState.Interrupt += OnSpineAnimationInterrupt;
   animationState.End += OnSpineAnimationEnd;
   animationState.Dispose += OnSpineAnimationDispose;
   animationState.Complete += OnSpineAnimationComplete;

   animationState.Event += OnUserDefinedEvent;

   // registering for events raised by a single animation track entry
   Spine.TrackEntry trackEntry = animationState.SetAnimation(trackIndex, "walk", true);
   trackEntry.Start += OnSpineAnimationStart;
   trackEntry.Interrupt += OnSpineAnimationInterrupt;
   trackEntry.End += OnSpineAnimationEnd;
   trackEntry.Dispose += OnSpineAnimationDispose;
   trackEntry.Complete += OnSpineAnimationComplete;
   trackEntry.Event += OnUserDefinedEvent;
}

public void OnSpineAnimationStart(TrackEntry trackEntry) {
   // Add your implementation code here to react to start events
}
public void OnSpineAnimationInterrupt(TrackEntry trackEntry) {
   // Add your implementation code here to react to interrupt events
}
public void OnSpineAnimationEnd(TrackEntry trackEntry) {
   // Add your implementation code here to react to end events
}
public void OnSpineAnimationDispose(TrackEntry trackEntry) {
   // Add your implementation code here to react to dispose events
}
public void OnSpineAnimationComplete(TrackEntry trackEntry) {
   // Add your implementation code here to react to complete events
}


string targetEventName = "targetEvent";
string targetEventNameInFolder = "eventFolderName/targetEvent";

public void OnUserDefinedEvent(Spine.TrackEntry trackEntry, Spine.Event e) {

   if (e.Data.Name == targetEventName) {
      // Add your implementation code here to react to user defined event
   }
}

// you can cache event data to save the string comparison
Spine.EventData targetEventData;
void Start () {
   targetEventData = skeletonAnimation.Skeleton.Data.FindEvent(targetEventName);
}
public void OnUserDefinedEvent(Spine.TrackEntry trackEntry, Spine.Event e) {

   if (e.Data == targetEventData) {
      // Add your implementation code here to react to user defined event
   }
}

See the Spine API Reference for detailled information.

Changing AnimationState or Game State in Callbacks

While you can modify AnimationState by e.g. calling AnimationState.SetAnimation() from within an AnimationState event callback, there are some potential timing issues to consider. This also applies when changing your game state from an event callback.

  1. AnimationState event callbacks are issued when animations are applied in SkeletonAnimation.Update(), before the mesh is updated in SkeletonAnimation.LateUpdate().
  2. If you call AnimationState.SetAnimation() from the AnimationState.End callback, it will trigger an AnimationState.Start event in the same frame.
  3. Because of mix transitions from one animation to another, the Start event of your second animation is issued before the End event of your first animation. This is a common pitfall to consider when modifying game state.

If you need to delay calls from within an event callback to the next Update() cycle, you could use StartCoroutine as follows:

C#
trackEntry.End += e => {
   StartCoroutine(NextFrame(() => {
      YourCode();
   }));
};

...

IEnumerator NextFrame (System.Action call) {
   yield return 0;
   if (call != null)
      call();
}

Coroutine Yield Instructions

The spine-unity runtime provides a set of yield instructions for use with Unity's Coroutines. If you are new to Unity Coroutines, the Coroutine tutorials and Coroutine documentation are a good place to start.

The following yield instructions are provided:

  1. WaitForSpineAnimation. Waits until a Spine.TrackEntry raises one of the specified events.

    C#
    var track = skeletonAnimation.state.SetAnimation(0, "interruptible", false);
    var completeOrEnd = WaitForSpineAnimation.AnimationEventTypes.Complete |
                          WaitForSpineAnimation.AnimationEventTypes.End;
    yield return new WaitForSpineAnimation(track, completeOrEnd);
  2. WaitForSpineAnimationComplete. Waits until a Spine.TrackEntry raises a Complete event.

    C#
    var track = skeletonAnimation.state.SetAnimation(0, "talk", false);
    yield return new WaitForSpineAnimationComplete(track);
  3. WaitForSpineAnimationEnd. Waits until a Spine.TrackEntry raises an End event.

    C#
    var track = skeletonAnimation.state.SetAnimation(0, "talk", false);
    yield return new WaitForSpineAnimationEnd(track);
  4. WaitForSpineEvent. Waits until a Spine.AnimationState raises a user-defined Spine.Event (named in Spine editor).

    C#
    yield return new WaitForSpineEvent(skeletonAnimation.state, "spawn bullet");
    // You can also pass a Spine.Event's Spine.EventData reference.
    Spine.EventData spawnBulletEvent; // cached in e.g. Start()
    ..
    yield return new WaitForSpineEvent(skeletonAnimation.state, spawnBulletEvent);

Note: Like Unity's built-in yield instructions, instances of these spine-unity yield instructions can be reused to prevent additional memory allocations.

Tutorial Page

You can find a tutorial page on spine-unity events here.

Scripting String Property Attributes

It is not convenient to type e.g. animation names manually in the Inspector. Thus spine-unity provides popup fields for string parameters instead. You can precede a string property with one of the following property attributes to automatically receive a popup selection field, populated with e.g. all available animations at a skeleton. If you can see such popup fields in one of the provided Spine components, you can also use the same popup via property attributes in your custom components. The following list shows available property attributes.

C#
[SpineBone] public string bone;
[SpineSlot] public string slot;
[SpineAttachment] public string attachment;
[SpineSkin] public string skin;
[SpineAnimation] public string animation;
[SpineEvent] public string event;
[SpineIkConstraint] public string ikConstraint;
[SpineTransformConstraint] public string transformConstraint;
[SpinePathConstraint] public string pathConstraint;

Please take a look at the example scenes that come with the spine-unity package to see the string property attributes in use.

SkeletonMecanim Component

The SkeletonMecanim component is one of three ways to use a Spine skeleton in Unity. These alternatives are: SkeletonAnimation, SkeletonMecanim and SkeletonGraphic (UI).

The SkeletonMecanim component is an alternative to the SkeletonAnimation component, using Unity's Mecanim animation system for high-level control in combination with the Spine animation system for posing and setup of the skeleton. The Mecanim system is used to determine which Spine animations shall be played back and determines track time and alpha of each animation. The respective Spine animations are then applied to the Spine skeleton by the component.

Like the SkeletonAnimation component, SkeletonMecanim allows you to add a Spine skeleton to a GameObject, animate it, react to animation events, and so on. After the animations are applied, before the skeleton is drawn, you can make changes to the skeleton just like you can when using SkeletonAnimation instead of SkeletonMecanim. In comparison to SkeletonAnimation it comes with some limitations and additional requirements:

Note: Compared to the SkeletonAnimation component, SkeletonMecanim requires additional timeline keys at the first frame of an animation if it shall smoothly mix out the timeline state of a preceding animation. See section Required Additional Keys below for more information.

Note: TrackEntry.MixAttachmentThreshold and similar mix threshold functionality is not available for SkeletonMecanim.

The SkeletonMecanim component provides similar parameters as the SkeletonAnimation component, please consult the SkeletonAnimation section for additional information.

Required Additional Keys

To smoothly mix out a timeline state (e.g. bone rotation) from one animation to the next, the second animation requires an additional key at the first frame when in setup pose. Otherwise the previous animation would leave a leftover timeline state. This is one of the drawbacks of SkeletonMecanim compared to SkeletonAnimation.

Short example: An idle animation shall smoothly mix out a preceding jump animation. Assuming jump ends with bones bone1 and bone2 keyed in non-setup-pose location, you have to add keys (in setup pose or any custom pose) at the first frame of the idle animation for bone1 and bone2 to properly mix out the jump state.

The Auto Reset parameter resets the state, but will mix out sharply at the end of an animation transition, not creating a smooth transition.

Also be sure to disable Animation cleanup upon exporting your skeleton as .json or .skel.bytes, otherwise keys identical to setup pose will not be exported!

Animation Blending Control

The SkeletonMecanim Inspector exposes the following additional parameters:

  • Mecanim Translator

    • Auto Reset. When set to true, the skeleton state is mixed out to setup pose when an animation finishes, according to the animation's keyed items. This may be especially important when an animation has changed attachment visibility state: when mixed out, attachment visibility will change back to setup pose state, otherwise current attachment state is held until another animation has a key set at the respective attachment timeline.

    • Custom MixMode. When disabled, the recommended MixMode is used according to the layer blend mode. When enabled, a Mix Modes section is shown below allowing you to specify a MixMode for each Mecanim layer.

    • Mix Modes. Shown when Custom MixMode parameter above is enabled. This parameter determines the animation mix mode between successive animations, and also across layers.

      • Mix Next (recommended for Base Layer and Override layers)
        Applies the previous track and then mixes in the next track on top using Mecanim transition weights.
      • Always Mix (recommended for Additive layers)
        Fades out the previous track (potentially to setup pose when Auto Reset is enabled), and mixes in the next track on top using Mecanim transition weights. Note that this may cause an unintended animation dipping effect when used on the base layer.
      • Hard (previously called Spine Style)
        Applies the next track immediately.
      • Match (new in 4.2, recommended on any layer using blend tree nodes)
        Calculates Spine animation weights to best match the provided Mecanim clip weights.

Result of Auto Reset and layer Mix Mode parameters

When a transition is active, there are four poses - current state last frame, the setup pose, previous clip pose and new clip pose - which will be combined as follows:

  1. Starts with current state last frame (or other modifications this frame prior to SkeletonMecanim's update).
  2. Apply setup pose:
    • When Auto Reset is enabled, the setup pose replaces the current state last frame.
    • When Auto Reset is disabled, setup pose is not part of the mix.

  3. Apply previous clip pose:
    • When mode is set to Always Mix, the previous clip pose is mixed with the current state (so mixed with setup pose when Auto Reset is enabled).
    • When set to Hard or Mix Next, the previous clip pose is applied with full weight, overriding the current state (thus overriding setup pose).

  4. Apply new clip pose:
    • When mode is set to Always Mix or Mix Next, the new clip pose is mixed with the current state. So at Always Mix with Auto Reset enabled it is a mix of setup pose, previous clip pose and new clip pose.
    • When mode is set to Hard, the new clip pose is applied with full weight, overriding all previously applied poses.

The table below shows the case when both previous clip P and new clip N modify the same timeline value, e.g. the same bone rotation. S represents the setup pose when Auto Reset is enabled, and the current state (e.g. of the previous frame) if disabled. Transition weight (0 at transition start, 1 at transition end) is represented by the variable w. The default (recommended) mix mode at each layer blend mode is highlighted in bold.

Always Mix Mix Next Hard
Base Layer lerp(lerp(S, P, 1-w), N, w) lerp(P, N, w) N
Override lerp(
lerp(lower_layers_result,
P, (1-w) * layer_weight),
N, w * layer_weight)
lerp(
lerp(lower_layers_result,
P, layer_weight),
N, w * layer_weight)
lerp(lower_layers_result,
N,
layer_weight)
Additive lower_layers_result +
layer_weight * lerp(P, N, w))
counts as Always Mix lower_layers_result +
layer_weight * N
Abbreviation Meaning
S Setup pose
P Previous clip pose
N New clip pose
w Transition weight
lerp(a, b, weight) Linear interpolation from a to b by weight.

Controller and Animator

The SkeletonMecanim component uses the Controller asset assigned at the Animator component as usual with Unity Mecanim. The Controller asset is automatically generated and assigned when instantiating a skeleton as SkeletonMecanim via drag and drop.

Note: When enabling Apply Root Motion a SkeletonMecanimRootMotion component is automatically added to your SkeletonMecanim GameObject.

You can add animations to the Controller's animation state machine via drag and drop of Spine animations to the Animator panel as usual. The animations can be found below the Controller asset.

Mix duration values set at the SkeletonDataAsset will be ignored by SkeletonMecanim. Instead, Mecanim transition times are used as setup via the Animator panel.

SkeletonMecanim Events

When using SkeletonMecanim, events are stored in each AnimationClip and are raised like other Unity animation events. For example, if you named your event "Footstep" in Spine, you need to provide a MonoBehaviour script on your SkeletonMecanim GameObject with a method named Footstep() to handle it. When using folders in Spine, the method name will be a concatenation of the folder name and the animation name. For example when the previous event is placed in a folder named Foldername it will be FoldernameFootstep().

C#
public class YourComponentReceivingEvents : MonoBehaviour {
   // to capture event "Footstep" when it's placed outside of folders
   void Footstep() {
      Debug.Log("Footstep event received");
   }

   // to capture event "Footstep" when it's placed in a folder named "Foldername"
   void FoldernameFootstep () {
      Debug.Log("Footstep (in folder Foldername) received");
   }
}

For more information on Unity Mecanim events, see Unity's Documentation on Animation Events.

SkeletonGraphic Component

The SkeletonGraphic component is one of three ways to use a Spine skeleton in Unity. These alternatives are: SkeletonAnimation, SkeletonMecanim and SkeletonGraphic (UI).

The SkeletonGraphic component is an alternative to the SkeletonAnimation component, using Unity's UI system for layout, rendering and mask interaction. As the SkeletonAnimation component, it allows you to add a Spine skeleton to a GameObject, animate it, react to animation events, and so on.

Why a specific UI Component

The Unity UI (UnityEngine.UI) uses a system of Canvas and CanvasRenderers to sort and manage its renderable objects. Built-in renderable UI components such as Text, Image, and RawImage, rely on CanvasRenderer to function correctly. Putting objects like MeshRenderers (e.g. a default Cube object), or SpriteRenderers (e.g. a Sprite) under a UI will not render in a Canvas. SkeletonAnimation uses a MeshRenderer and thus behaves in the same way. The spine-unity runtime therefore provides the SkeletonAnimation variant SkeletonGraphic, a subclass of UnityEngine.UI.MaskableGraphic using CanvasRenderer components for rendering.

Important Material Requirements

Only use Materials with special CanvasRenderer compatible shaders at SkeletonGraphic components, such as the Spine/SkeletonGraphic* shaders which are assigned by default. Do not use URP, LWRP or normal shaders like Spine/Skeleton with a SkeletonGraphic component. Seeing no visual error does not mean that the shader works with SkeletonGraphic. We have seen cases where it renders incorrectly on target mobile devices while rendering without any issues in the Unity Editor. As other UI components, SkeletonGraphic uses a CanvasRenderer instead of a MeshRenderer, which uses a separate rendering pipeline.

Normal Materials assigned at a SpineAtlasAsset are ignored when instantiating a SkeletonDataAsset as SkeletonGraphic, only the Textures are used. You can use a SkeletonGraphicCustomMaterials component to override Materials at a SkeletonGraphic component.

Important Note: due to limitations of the used Unity CanvasRenderer, SkeletonGraphic is limited to a single texture by default. You can enable Advanced - Multiple CanvasRenderers at the SkeletonGraphic component Inspector to generate a child CanvasRenderer GameObject for every submesh to raise the texture limit. For performance reasons, this is better avoided where possible. This means Skeletons used in UI shall be packed as a single-texture (single-page) atlas, rather than multi-page atlases. See section Advanced - Single Atlas Texture Export and SkeletonGraphic on how to pack attachments to a single atlas page texture.

Correct Configuration and Materials

Using special shaders like "Spine/SkeletonGraphic Tint Black" or using SkeletonGraphic below a CanvasGroup requires vertex data to be generated accordingly. You can find the relevant parameters in the Advanced - Vertex Data Inspector section. The settings are Tint Black, CanvasGroup Compatible and PMA Vertex Color. We have provided Detect buttons next to each property which automatically derives the correct settings. There is also a Detect Settings button which detects settings for all three properties.

After modifying Advanced - Vertex Data settings, the used materials need to be updated to fit the active settings. At SkeletonGraphic, materials are independent of textures, and can thus be shared across different skeletons which use the same material properties. For this reason, special shared SkeletonGraphic materials are provided for the main parameter and shader combinations. The suitable material can be assigned automatically according to the chosen Advanced - Vertex Data settings via the available Detect button next to the Material property.

When the skeleton uses multiple blend modes and has Advanced - Multiple CanvasRenderers enabled, you can use the Detect button next to Blend Mode Materials to automatically assign the suitable blend mode materials in a similar way.

If you receive incorrect results, likely your atlas texture's import settings are incorrect (see the documentation here).

CanvasGroup alpha

When using Spine/SkeletonGraphic* shaders with a CanvasGroup, you will notice the skeleton becoming brighter when reducing the CanvasGroup Alpha value, as can be seen in the image below.

This is due to Unity modifying the vertex color alpha value behind the scenes, which unfortunately does not play well with the premultiplied-alpha vertex color shaders of the spine-unity runtime.

Important Note: The spine-unity 4.2 and newer runtimes provide Detect buttons to automatically assign correct settings at parameters of the Advanced - Vertex Data section and a Detect Material button to automatically assign the suitable material based on the active settings. You can skip the sections below unless you need detailed information.

SkeletonGraphic without Tint Black

The following applies When using a material with the Spine/SkeletonGraphic shaders except for Spine/SkeletonGraphic TintBlack*. If you use such a material below a CanvasGroup with alpha fadeout, the material must have the parameter CanvasGroup Compatible enabled and the SkeletonGraphic component PMA Vertex Colors disabled:

  1. a) With version 4.2 and newer of the spine-unity runtime, you can find a CanvasGroup Compatible variant of each material in the folders Materials/SkeletonGraphic-PMATexture/CanvasGroup and Materials/SkeletonGraphic-StaightAlphaTexture/CanvasGroup respectively.
    b) On older versions, best create a copy of the shared SkeletonGraphicDefault material and rename it to e.g. SkeletonGraphic CanvasGroup instead of modifying the original material. Note that this shared SkeletonGraphic material needs to be created only once, it can be used with different skeletons as it is independent of the used texture.

  2. Assign this CanvasGroup Compatible material at any SkeletonGraphic components below a CanvasGroup instead of the original material.

  3. Any SkeletonGraphic component using this CanvasGroup compatible material needs to also have Advanced - PMA Vertex Colors disabled to avoid a double-darkening effect of semi-transparent parts. This unfortunately prevents rendering of additive slots in a single batch together with normal slots and may thus increase the number of draw calls.

SkeletonGraphic TintBlack

When using a material with the Spine/SkeletonGraphic TintBlack* shader below a CanvasGroup with alpha fadeout, the following setup is required:

  1. a) As above, with spine-unity version 4.2 and newer, use the provided SkeletonGraphic TintBlack materials within the CanvasGroupCompatible folder, or
    b) on older versions create a copy of the shared SkeletonGraphicTintBlack material and rename it to e.g. SkeletonGraphicTintBlack CanvasGroup instead of modifying the original material. Note that this shared SkeletonGraphic material needs to be created only once, it can be used with different skeletons as it is independent of the used texture.
  2. Assign this material at the SkeletonGraphic component instead of the original material.
  3. Enable Advanced - CanvasGroup Compatible at the SkeletonGraphic component
    (Advanced - Canvas Group Tint Black on version 4.1 or older).
  4. a) When using spine-unity 4.2 or newer, both enabled and disabled Advanced - PMA Vertex Colors SkeletonGraphic settings are supported. It is recommended to keep Advanced - PMA Vertex Colors enabled to benefit from rendering additive slots in a single draw call.
    b) On older versions, disable Advanced - PMA Vertex Colors to avoid a double-darkening effect of semi-transparent additive slots.

Bounds and Correct Visibility

Visibility of a SkeletonGraphic is determined via its RectTransform bounds. When a Skeleton is instantiated via drag-and-drop as a child of a Canvas GameObject, the RectTransform bounds are automatically matched to the initial pose. You can also manually fit the RectTransform to its current pose's dimensions by clicking the Match RectTransform with Mesh button. It is important that the RectTransform bounds are not smaller than the mesh, otherwise e.g. a RectMask2D will omit drawing the skeleton as soon as the RectTransform is completely outside, even when part of the mesh is still inside and should be rendered. The current RectTransform bounds are shown in Scene view when the RectTransform Tool of the five Transform modes is active.

Parameters

SkeletonGraphic provides similar parameters as the SkeletonAnimation component, please consult the SkeletonAnimation section for additional information.

The SkeletonGraphic Inspector exposes the following additional parameters:

  • Material - Detect button. Assigns the suitable "Spine/SkeletonGraphic*" material, according to Advanced - Vertex Data settings. Same as Detect Material parameter in the Advanced section below.

  • Freeze. When set to true, the SkeletonGraphic will no longer be updated.

  • Layout Scale Mode. SkeletonGraphic supports automatic uniform scaling based on its RectTransform bounds. Defaults to None to keep previous behaviour. Automatic scaling can be enabled by setting this parameter to Width Controls Height, Height Controls Width, Fit In Parent or Envelope Parent (details can be found here). To modify the reference layout bounds, hit the Edit Layout Bounds toggle button to enter edit-mode, allowing you to adjust the bounds to your skeleton. The skeleton will be scaled accordingly to fit the reference layout bounds to the object's RectTransform.

  • Edit Layout Bounds. To modify the reference layout bounds used by Layout Scale Mode above, hit this toggle button to enter edit-mode. You can then adjust the bounds manually or hit Match RectTransform with Mesh to fit the current pose. When done adjusting, hit the Edit Layout Bounds toggle button again to exit edit-mode.

  • Match RectTransform with Mesh You can make a SkeletonGraphic's RectTransform fit its current pose's dimensions by clicking the Match button. It is important that the RectTransform bounds are not smaller than the mesh, otherwise e.g. a RectMask2D will omit drawing the skeleton as soon as the RectTransform is outside, even when part of the mesh is still inside and should be rendered. This option is grayed-out unless Layout Scale Mode is set to None or the Edit Layout Bounds toggle button is set to edit-mode.

  • Advanced

    • Use Clipping. When set to false, any Spine clipping attachments will be ignored.

    • Tint Black (!). Adds black tint vertex data to the mesh. Enable if the skeleton has any slots with tint black color set.
      Black tinting requires that the shader interprets UV2 and UV3 as black tint colors, such as the provided Spine/SkeletonGraphic Tint Black* shaders.
      To allow UV2 and UV3 data at the parent Canvas, you need to select the Canvas and under Additional Shader Channels enable TexCoord1 and TexCoord2.

      A Detect button is provided which enables this parameter if the SkeletonData contains any slot with tint black color set, and disables it otherwise.

    • CanvasGroup Compatible. Enable when SkeletonGraphic is used below a CanvasGroup GameObject. The material also needs CanvasGroup Compatible enabled, so assign the suitable material after changing this setting via Detect Material or manually.
      When using a SkeletonGraphic Tint Black* shader and both Tint Black and PMA Vertex Color are enabled, the alpha value will be stored at uv2.g instead of at the primary vertex color color.a, and color.a stores constant 1.0 to capture CanvasGroup modifying color.a.

      A Detect button is provided which enables this parameter if the SkeletonGraphic component is located below a CanvasGroup component in the hierarchy, and disables it otherwise.

    • [4.1 and older] Canvas Group Tint Black. Only enable when using a SkeletonGraphic Tint Black* shader. Has no effect when Tint Black is disabled or PMA Vertex Color is disabled. Enable when using Additive blend mode at a slot of SkeletonGraphic under a CanvasGroup. When enabled, the alpha value is stored at uv2.g instead of primary vertex color color.a, and color.a stores constant 1.0 to capture CanvasGroup modifying color.a.

    • PMA Vertex Colors (additional rules for CanvasGroup alpha apply). Multiply vertex color RGB with vertex color alpha. This parameter is enabled by default, which is the correct setting unless you are using thirdparty shaders or require CanvasGroup Compatible enabled on a shader which is not "SkeletonGraphic TintBlack*".

      A Detect button is provided, which requires Tint Black and CanvasGroup Compatible above to be setup correctly. Detect disables this parameter if a thirdparty (non-Spine) shader is used, or if CanvasGroup Compatible is enabled and Tint Black disabled. It enables the parameter otherwise.

      The following detailed rules for PMA Vertex Color apply (only needed when Detect fails):

      When using spine-unity 4.2 or newer:
      Enable this parameter (the default):

      • if CanvasGroup Compatible is disabled at the used "Spine/SkeletonGraphic*" shader (even with Straight Alpha Texture enabled), or
      • if using a "Spine/SkeletonGraphic TintBlack*" shader (even with Straight Alpha Texture enabled), or
      • if using a thirdparty (non-Spine) shader which requires vertex color as PMA (likely if the shader uses PMA additive output blend mode Blend One OneMinusSrcAlpha).

      Disable this parameter:

      • if not using a "Spine/SkeletonGraphic TintBlack*" shader but a normal "Spine/SkeletonGraphic*" shader which has CanvasGroup Compatible enabled, or
      • if using a thirdparty (non-Spine) shader which requires regular vertex color (likely if the shader uses regular output blend mode Blend SrcAlpha OneMinusSrcAlpha).

      When using spine-unity 4.1 or older:
      Enable this parameter (the default):

      • if CanvasGroup Compatible is disabled at the used "Spine/SkeletonGraphic*" shader (even with Straight Alpha Texture enabled), or
      • if using a thirdparty (non-Spine) shader which requires vertex color as PMA (likely if the shader uses PMA additive output blend mode Blend One OneMinusSrcAlpha).

      Disable this parameter:

      • if you're using a "Spine/SkeletonGraphic*" shader which has CanvasGroup Compatible enabled, or
      • if using a thirdparty (non-Spine) shader which requires regular vertex color (likely if the shader uses regular output blend mode Blend SrcAlpha OneMinusSrcAlpha).

      When enabled, additive slots can be rendered in a single draw call together with normal slots. When disabled, additive slots require SkeletonData Blend Mode Materials - Apply Additive Material enabled, leading to a separate draw call, which may adversely affect performance.

    • Detect Settings. Applies detection of Tint Black, CanvasGroup Compatible and PMA Vertex Colors parameters at once.

    • Detect Material. Assigns the suitable SkeletonGraphic material based on the above Tint Black and CanvasGroup Compatible parameters and the atlas texture's import settings (PMA vs straight alpha settings). If you receive incorrect results, likely your texture settings are incorrect (see the documentation here).

    • Multiple CanvasRenderers. When set to true, SkeletonGraphic no longer uses a single CanvasRenderer but automatically creates the required number of child CanvasRenderer GameObjects for each required draw call (submesh). This can be used to raise the single texture limitation, but comes at an additional performance overhead.

      • Blend Mode Materials. Allows using different SkeletonGraphic materials for each Slot blend mode. Use only "Spine/SkeletonGraphic *" or other CanvasRenderer compatible materials here.

      • Select Assign Default to assign the default blend mode materials SkeletonGraphicAdditive, SkeletonGraphicMultiply and SkeletonGraphicScreen.

        Note: Be sure to have a proper setup of Blend Mode Materials at the SkeletonDataAsset, as the SkeletonGraphic blend mode material assignment relies on the SkeletonDataAsset's materials. Additive Material is ignored when PMA Vertex Colors is enabled.

    • Animation Update. Whether to update the animation in normal Update (the default), physics step FixedUpdate, or manually via a user call. When using a SkeletonRootMotion component with a Rigidbody or Rigidbody2D assigned, it is recommended to set the update mode to In FixedUpdate. Otherwise In Update is recommended.

    • Update When Invisible. Update mode used when the MeshRenderer becomes invisible. Update mode is automatically reset to UpdateMode.FullUpdate when the mesh becomes visible again.

    • Separator Slot Names. Slots that determine where the render is split when Enable Separation is set to true. For general information on render separation, see section SkeletonRenderSeparator, but note that no additional components are required with SkeletonGraphic.

    • Enable Separation. Render separation can be enabled directly in this Inspector section, it does not require any additional components (like SkeletonRenderSeparator or SkeletonPartsRenderer for SkeletonRenderer components). When enabled, additional separation part GameObjects will be created automatically, and CanvasRenderer GameObjects re-parented to them accordingly. The separation part GameObjects can be moved around and re-parented in the hierarchy according to your requirements to achieve the desired draw order within your Canvas.

    • Update Part Location. When enabled, separator part GameObject location will be updated to match the position of the SkeletonGraphic. This can be helpful when re-parenting parts to a different GameObject.

    • Physics Inheritance. Controls how Transform movement is applied to PhysicsConstraints of the skeleton.

      • Position. When set to non-zero, Transform position movement in X and Y direction is applied to skeleton PhysicsConstraints, multiplied by these X and Y scale factors. Typical (X,Y) values are:
        (1,1) to apply XY movement normally,
        (2,2) to apply movement with double intensity,
        (1,0) to apply only horizontal movement, or
        (0,0) to not apply any Transform position movement at all.
      • Rotation. When set to non-zero, Transform rotation movement is applied to skeleton PhysicsConstraints, multiplied by this scale factor. Typical values are:
        1 to apply movement normally,
        2 to apply movement with double intensity, or
        0 to not apply any Transform rotation movement at all.
      • Movement relative to. To apply Transform movement relative to e.g. a parent Transform, set this to the reference Transform relative to which movement shall be calculated. Set this to None to use the absolute world location (the default).

Example Scene

You can examine the example scene Spine Examples/Getting Started/6 Skeleton Graphic for basic usage.
An advanced example scene showing how to set up separator slots and modify draw order can be found at Spine Examples/Other Examples/SkeletonRenderSeparator.

SkeletonRenderer Component

The SkeletonRenderer component is responsible for drawing the current state of a skeleton. It is the base class for SkeletonAnimation and SkeletonMecanim.

Note: most of the time you will want to use SkeletonAnimation, SkeletonMecanim or SkeletonGraphic (UI) instead. These components provide sophisticated means to control animation. Only when applying animations manually without transitions, as could be useful at a UI gauge element, this component may be useful as-is.

Rendering is performed via a procedural mesh which is updated at a MeshRenderer component. The component uses the texture atlas asset referenced by the SkeletonDataAsset to find the textures and materials needed to draw the attachments of the skeleton. Please consult the documentation section of SkeletonAnimation for additional information.

You can examine the example scene Spine Examples/Other Examples/SpineGauge on how to use a SkeletonRenderer component directly.

Next: Utility Components Previous: Assets