how to attach script to object created only in runtime unity
spine-unity Runtime Documentation
Licensing
Integrating an official Spine Runtime into your applications requires a valid Spine license, though you are welcome to use the Spine Runtimes for evaluation purposes.
Getting Started
Installation
To use the spine-unity runtime in your Unity project:
- Download and install Unity.
- Create a new empty project in the Unity Editor.
- Download the latest spine-unity unitypackage. Alternatively you can get the latest changes via Git as described below.
- Import the unitypackage (you can double-click on it and Unity will open it).
Getting latest changes via Git instead of the unitypackage
- Clone the spine-runtimes Git repository.
- Copy the contents of
spine-runtimes/spine-unity/Assets/
to your project'sAssets/
folder.- Copy the folder
spine-runtimes/spine-csharp/src
to your project'sAssets/Spine/Runtime/spine-csharp
folder.
2D Toolkit Compatibility
spine-unity supports 2D Toolkit and can render Spine skeletons using TK2D's texture atlas system. To enable 2D Toolkit compatibility, open Unity's Preferences
via Edit - Preferences
(Unity - Preferences
on Mac) and in section Spine
select Define TK2D
- Enable
.
Optional Extension UPM Packages
The spine-unity runtime works without additional plugins. Some optional features, such as Timeline or Universal Render Pipeline support, are provided via separate Unity Package Manager (UPM) extension packages.
Why separate extension packages
Unity has moved many of their optional modules to the new Unity Package Manager (UPM) ecosystem. For example, their Universal Render Pipeline base shader files are also provided as a UPM package under the name Universal RP
and not part of every new Unity project out of the box.
Including our Universal RP Spine shaders in the spine-unity runtime would lead to confusing error messages and additional configuration steps in case Unity's Universal RP
package has not been installed in a project. By providing our Universal RP Spine shaders as a UPM package, such dependencies are automatically resolved, making it easier to use this additional functionality.
Installation
- Download the desired UPM package via the download page or find it in the spine-unity/Modules subdirectory in the Git repository.
- If you have your Unity project open, it is recommended to either
- a) close Unity or
- b) close any scene containing Spine components (e.g. by opening a new empty scene).
- After unzipping or cloning, you can make use of the package in one of these two ways:
Samples
To explore the spine-unity runtime example scenes:
- Download and install Unity.
- Create a new empty project in the Unity Editor.
- Download the latest spine-unity unitypackage. Alternatively you can get the latest changes via Git as described below.
- Import the unitypackage (you can double-click on it and Unity will open it).
- Open the project in the Unity Editor, then checkout the different example scenes in the
Spine Examples/Getting Started
folder in the Project panel. Each example scene has text instructions on how to run it and a description of what you see.
Getting latest changes via Git instead of the unitypackage
- Clone the spine-runtimes Git repository.
- Copy the contents of
spine-runtimes/spine-unity/Assets/
to your project'sAssets/
folder.- Copy the folder
spine-runtimes/spine-csharp/src
to your project'sAssets/Spine/Runtime/spine-csharp
folder.
You can inspect and modify the C# code of both the samples and the spine-unity runtime by opening the project in Unity Editor and selecting Assets -> Open C# Project
. For additional information on the example scenes, please see section Example Scenes.
Updating the spine-unity Runtime
Before updating your project' spine-unity runtime, please consult our guide on Spine editor and runtime version management.
Note: Json and binary skeleton data files exported from Spine 3.8 or earlier will not be readable by the spine-unity 4.0 runtime! The skeleton data files need to be re-exported using Spine 4.0.
If you have many projects, we suggest automating exporting your project files as described here.
For example, we use this script to export all the Spine example projects and to create texture atlases: export.sh
Please consult the following upgrade guides when updating from spine-unity 3.6, 3.7 or 3.8 to newer versions:
- spine-unity 3.6 to 3.7 Upgrade-Guide
- spine-unity 3.7 to 3.8 Upgrade-Guide
- spine-unity 3.8 to 4.0 Upgrade-Guide
It is recommended to perform the following steps to prevent potential problems:
- As with Unity updates, it is always recommended that you back up your whole Unity project before performing an update.
- Always check with your Lead Programmer and Technical Artist before updating your Spine runtime. Spine runtimes are source-available and designed to be user-modifiable based on varying project needs. Your project's Spine runtime may have been modified by your programmer. In this case, updating to the latest runtime also requires reapplying those modifications to the new version of the runtime.
- Read the
CHANGELOG.md
file included in the downloaded unitypackage or on github. You can find the necessary documentation here when obsolete methods have been replaced with new counterparts.
Once you are sure you want to update to the latest spine-unity runtime:
- Get the latest spine-unity runtime by downloading the latest spine-unity unitypackage. Alternatively you can update by pulling the latest changes from the spine-runtimes Git repository via Git as described below.
- Close the Unity Editor and Visual Studio/Xcode.
- When upgrading to a different major or minor version (e.g. from 3.7 to 3.8), delete the previous spine-unity installation directories
Assets/Spine
andAssets/Spine Examples
from your project. - Open the project in the Unity Editor. In case you removed the previous spine-unity installation, ignore any logged errors.
- Import the unitypackage (you can double-click on it and Unity will open it).
- When upgrading to a different major or minor version, re-import the skeleton assets by selecting
right-click - Reimport All
in the Project panel. Alternatively to not re-import all assets, you can locate the folder containing your Spine skeleton assets in the Project panel that you want to re-import, right-click on the folder, then selectReimport
.
Getting latest changes via Git instead of the unitypackage
- Get the latest spine-unity runtime by pulling the latest changes from the spine-runtimes Git repository.
- When upgrading to a different major or minor version (e.g. from 3.7 to 3.8), delete the previous spine-unity installation directories
Assets/Spine
andAssets/Spine Examples
from your project.- Copy the contents of
spine-runtimes/spine-unity/Assets/
to your project'sAssets/
folder.- Copy the folder
spine-runtimes/spine-csharp/src
to your project'sAssets/Spine/Runtime/spine-csharp
folder.
Note: The spine-unity runtime is based on the generic spine-csharp runtime. Make sure to watch changes to both the spine-unity and spine-csharp runtime on GitHub.
Updating an Extension UPM Package
When upgrading an optional extension UPM package:
- The same principles as updating the Spine Unity runtime apply.
- As mentioned above, it is always recommended that you back up your whole Unity project before performing an update.
In-place Update (via .zip file or git)
- If you have your Unity project open, it is recommended to either a) close Unity or b) close any scene containing Spine components (e.g. by opening a new empty scene).
- Copy the content of the new UPM package zip file or git directory over the existing one. Depending on how you have installed the UPM package, this will be either the
project_root/Packages/package_name
directory in your project or the arbitrary directory outside theAssets
directory from where you have loaded it viaAdd package from disk..
. - If you have closed Unity, open your project again in Unity.
- Unity will import the new assets and display a loading progress bar.
Scripting in Unity
If you are not familiar with programming in C# and using Unity in general, we recommend watching the official Unity Tutorials first. The Unity Essentials and then Scripting topics are a good place to start. Note that the Animation topic is not directly applicable to spine-unity since Spine provides its own animation workflow.
Using the spine-unity Runtime
Overview
The spine-unity runtime is a Unity plugin supporting playback and manipulation of animations created with Spine. The spine-unity runtime is written in C# and based on the generic spine-csharp runtime. The spine-unity runtime wraps the spine-csharp structs and functions and exposes them as Unity components. Additionally, the spine-unity runtime imports files exported from the Spine Editor and stores them in custom Unity asset types.
Please consult the Spine Runtimes Guide for a detailed overview of the Spine Runtime architecture.
Asset Management
Exporting Spine Assets for Unity
Export User Guide
You can find complete instructions in the Spine User Guide on how to
- Export skeleton & animation data
- Export texture atlases containing the images of your skeleton
Spine Unity Export for Beginners
The following shows a simple way to export Spine assets for Unity.
-
After you have created your skeleton and animations, click on
Spine Menu
>Export...
(CTRL
+E
). This opens the Export window.
-
Choose
JSON
on the upper-left of the Export window.
-
Check the
Texture Atlas
Pack
checkbox. (CheckingNonessential data
,Pretty print
are also recommended for beginners). Be sure to haveAnimation cleanup
disabled, otherwise keys identical to setup pose will not be exported.
- Click on
Pack Settings
below thePack
checkbox. This opens the Texture Packer Settings window. - On the lower-right, look for the textbox labeled
Atlas extension
and make sure it is set to.atlas.txt
. - You're done with the Texture Packer Settings window. Click
OK
to close.
- Click on
-
In the Export window, pick an output folder. (Recommendation: Create a new empty folder.)
-
Click
Export
. -
This will export three files:
-
skeleton-name.json
orskeleton-name.skel.bytes
, containing your skeleton and animation data. -
skeleton-name.atlas.txt
, containing information about the texture atlas. - One or more
.png
files, each representing on page of your texture atlas containing the packed images your skeleton uses.
-
Note: For 2D Toolkit users, Step 3 (packing a
.png
and.atlas.txt
) is not necessary. Instead, you will have the appropriate field in your SkeletonDataAsset to assign a reference totk2dSpriteCollectionData
. Please consult the Installation section of this page on how to enable 2D Toolkit support.
Binary Export for Unity
Exporting in binary format instead of JSON will result in smaller file size and faster loading.
The following shows how to change to binary export for spine-unity.
- Choose
Binary
on the upper-left of the Export window instead ofJSON
. - Set the
Extension
to.skel.bytes
.
Note: spine-unity cannot load files with extension
.skel
. Be sure to use extension.skel.bytes
.
Advanced - Single Texture Atlas Export and SkeletonGraphic
It is recommended in general to use a single-texture (single-page) atlas where possible to reduce the number of draw calls caused by additional submeshes. This is especially true for SkeletonGraphic. 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 best avoided where possible. This means Skeletons used in UI shall be packed as a single-texture (single-page) atlas, rather than multi-page atlases.
If they do not fit into a single atlas page, you can pack texture atlas pages grouped by folder. This way you can ensure that each skin requires only a single atlas page.
When the images are placed in the respective folders, you can export the skeleton with the following steps:
- Press
Ctrl+E
or in the dropdown menu selectExport...
- Enable
Texture Atlas
Pack
and selectImage Folder
instead ofAttachments
right to it. - (optional) Check in
Pack Settings
if underOptions
in the bottom rightFlatten Paths
andCombine Subdirectories
is disabled (this is the default). - Click Export.
Advanced - Premultiplied vs Straight Alpha Export
Spine offers two basic workflows via Texture Packer Settings how atlas textures can be exported:
- Premultiplied alpha (the default, premultiplied in Gamma color space)
- Straight alpha
Premultiplied alpha workflow offers some advantages over straight alpha, no additional draw calls for additive-blended attachments and better mip-map generation being two of them.
It is very important to match export and import settings correctly, see section Advanced - Premultiplied vs Straight Alpha Import for correct settings in Unity.
Importing Spine Assets into Unity
- Open your Unity project in the Unity Editor. It should already have a functioning spine-unity runtime in it, as described in section Installation.
- Open the folder of the exported files. (
.json
,.atlas.txt
and.png
) - Copy the exported files (or the folder containing them) to your desired subfolder of your project's
Assets
folder. You can do this by dragging the exported files from an Explorer/Finder window into your desired folder in Unity's Project panel.
The spine-unity runtime will automatically generate the necessary additional Unity assets upon detecting the added files.
The following assets are generated:
- an _Atlas asset for the texture atlas file (
.atlas.txt
). It holds a reference to the material and the.atlas.txt
file. - a _Material asset for each texture atlas page (
.png
). It holds references to the shader and the.png
texture. - a _SkeletonData asset for skeleton data files (
.json
,.skel.bytes
). It holds a reference to the.json
or.skel.bytes
file and the generated _Atlas asset. It additionally provides custom import and animation settings for your skeleton, see section Skeleton Data Asset.
Advanced - Premultiplied vs Straight Alpha Import
As described in Advanced - Premultiplied vs Straight Alpha Export, Spine offers two basic workflows of how atlas textures can be exported:
- Premultiplied alpha (the default, premultiplied in Gamma color space)
- Straight alpha
Preferences parameter Atlas Texture Settings
for correct import settings
Important Note: It is very important that whenever the Premultiply alpha
setting is enabled upon atlas texture export, both the Material's Straight Alpha Texture
parameter and the Texture's Alpha Is Transparency
setting in Unity are disabled and vice versa. The spine-unity runtime provides a Spine
preferences section in Unity's Preferences
window, accessible via Edit - Preferences
(Unity - Preferences
on Mac). It provides an Atlas Texture Settings parameter to automatically apply the proper texture and material import settings at newly imported atlas textures.
When exporting atlas textures from Spine with Premultiply alpha
enabled (the default), you can leave it at PMATexturePreset
. If you have disabled Premultiply alpha
, set it to StraightAlphaTexturePreset
. You can also create your own TextureImporter
Preset
asset and assign it here.
Whenever you see dark borders around transparent areas, or colorful stripes around your attachment images, it is very likely because of incorrect import settings.
Correct Texture Packer export and Texture and Material import settings:
-
Premultiplied Alpha Texture Packer setting
Premultiply alpha
enabled,
Unity Texture settingssRGB (Color Texture)
enabled andAlpha Is Transparency
disabled,
Unity Material parameterStraight Alpha Texture
disabled. -
Straight Alpha Texture Packer setting
Premultiply alpha
disabled,Bleed
enabled,
Unity Texture settingssRGB (Color Texture)
enabled andAlpha Is Transparency
enabled,
Unity Material parameterStraight Alpha Texture
enabled.
The default texture packer settings use Premultiply alpha
. All Spine shaders that come with the spine-unity runtime are also configured to use Premultiply alpha
workflow by default, they have the Straight Alpha Texture
parameter disabled as default.
There might are use cases however, where you may want to use straight alpha workflow. Some of the use cases are:
- When using Linear color space, you must use straight alpha.
The premultiplication is performed in Gamma space upon export, which will cause incorrect borders when converted back to Linear space on import. You will receive a log warning message when this combination is detected at a material. - When you want to use a shader other than the included Spine shaders.
Typically shaders will assume straight alpha textures, which will lead to incorrect black borders around attachment images.
Be sure to configure all textures and materials accordingly as described above when switching to straight alpha workflow. You can check or modify the current color space via Project Settings - Player - Other Settings - Color Space
.
Advanced - Using Unity SpriteAtlas as Atlas Provider
Note: It is encouraged to follow the normal Spine workflow and use sprite atlases created by Spine instead of Unity
Sprite Atlas
assets. Spine atlases provide superior packing, support multiple atlas pages and are less prone to problems. Use Unity'sSprite Atlas
assets as an atlas provider only when you cannot use the normal Spine workflow. Also consider that you can re-pack Spine sprite atlases from single attachments at runtime.
You can use Unity's SpriteAtlas
as atlas provider as an alternative to .atlas.txt
and .png
files alongside a skeleton data file. Import is handled via a special Spine SpriteAtlas Import
tool window accessible via Window - Spine - SpriteAtlas Import
.
Steps to prepare the Sprite Atlas
:
- Create a
Sprite Atlas
viaAssets - Create - Sprite Atlas
. - Add the folder containing the Sprites to be used as attachments to
Objects for Packing
in theSprite Atlas
Inspector. - (a) For Unity versions prior to 2018.2, please manually disable
Tight Packing
and enableRead/Write Enabled
.
(b) in Unity versions 2018.2 an newer, these settings are automatically adjusted for you. - Assign the
Sprite Atlas
to theSprite Atlas
property in the newSpine SpriteAtlas Import
window. Additional assets are generated automatically. - Hit
Load regions by entering Play mode
to briefly switch into play mode and back again to load the region information. YourSprite Atlas
is now ready for use as a Spine atlas.
To use the atlas at a .json
or .skel.bytes
skeleton asset:
- Place the
.json
or.skel.bytes
file in the same directory as the newly created atlas assets. - Assign it to the
Skeleton json/skel file
property in theSpine SpriteAtlas Import
window. - Hit
Import Skeleton
to generate the_SkeletonData
file using theSprite Atlas
assets.
Spine Preferences
The spine-unity runtime provides a Spine
section in Unity's Preferences
window, accessible via Edit - Preferences
(Unity - Preferences
on Mac). Here you can setup default values used upon skeleton import and instantiation, as well as customize appearance and update behaviour of the spine-unity runtime.
- Show Hierarchy Icons. Show relevant icons next to
GameObjects
in the Hierarchy panel with Spine components on them. - Auto-reload scene components. Reloads skeleton components in the scene whenever their SkeletonDataAsset is modified. This may be slow when your scenes have large numbers of SkeletonRenderer or SkeletonGraphic components.
- Auto-Import Settings
- Default Mix. The Default Mix Duration for newly imported SkeletonDataAssets.
- Default SkeletonData Scale. The default
Scale
value for newly imported SkeletonDataAssets. - Default Shader. The default shader assigned at materials created for newly imported skeleton atlas textures.
- Apply Atlas Texture Settings. Apply reference
Atlas Texture Settings
at texture importers specified below. - Atlas Texture Settings. Apply the selected texture import settings at newly imported atlas textures and materials. When exporting atlas textures from Spine with
Premultiply alpha
enabled (the default), you can leave it atPMATexturePreset
. If you have disabledPremultiply alpha
, set it toStraightAlphaTexturePreset
. You can also create your ownTextureImporter
Preset
asset and assign it here. - Additive Material. Material template for slot blend mode
Additive
. SeeSkeletonData
Blend Mode Materials. - Multiply Material. Material template for slot blend mode
Multiply
. SeeSkeletonData
Blend Mode Materials. - Screen Material. Material template for slot blend mode
Screen
. SeeSkeletonData
Blend Mode Materials.
- Warnings
- Atlas Extension Warning. Log a warning and recommendation whenever a
.atlas
file is found. - Texture Settings Warning. Log a warning and recommendation whenever texture import settings are detected that could lead to undesired effects, e.g. white border artifacts.
- Atlas Extension Warning. Log a warning and recommendation whenever a
- Editor Instantiation
- Default Slot Z-Spacing. The default Z Spacing parameter of newly instantiated SkeletonRenderer or SkeletonGraphic components.
- Default Loop. The default
Loop
parameter of newly instantiated SkeletonRenderer or SkeletonGraphic components.
- Mecanim Bake Settings
- Include Folder Name in Event. When enabled, Mecanim events will call methods named
"FolderNameEventName"
, when disabled it will call"EventName"
.
- Include Folder Name in Event. When enabled, Mecanim events will call methods named
- Handles and Gizmos
- Editor Bone Scale. Size of bones and similar gizmo elements displayed in the Scene view.
- Timeline Extension - relevant for the Timeline Extension UPM Package
- Use Blend Duration. The default
Use Blend Duration
parameter of newly createdSpine Animation State Clips
.
- Use Blend Duration. The default
Updating Spine Assets
During development, you may frequently update your Spine skeleton data and texture atlas files. You can simply overwrite these files (.json
, .skel.bytes
, .atlas.txt
, .png
). Re-export the assets from the Spine Editor and copy the exported files to your subfolder of your project's Assets
folder again, overwriting the existing files.
Unity will detect changes to these files and automatically re-import the modified assets. After re-import, all references to previously imported Spine assets will be intact and use the latest data.
Note: Unity sometimes fails to recognize file changes. In this case, locate the folder containing the Spine assets in Unity's Project panel that you want to re-import, right-click on the folder, then select
Reimport
from the context menu.
Skeleton Data Asset
The skeleton data asset (named with suffix _SkeletonData
) stores information about the bone hierarchy, slots, draw order, animations and other data that constitutes your skeleton. Other components provided by the spine-unity runtime reference and share this skeleton data asset to animate and display a skeleton.
To inspect or modify a skeleton data asset, select it in Unity's Project panel. The Inspector panel will display all properties of the skeleton data for review and modification.
Skeleton Data
The SkeletonData section provides general import settings of the skeleton.
-
Scale. Allows you to specify a custom import scale value, affecting all skeleton instances referencing this data asset. Changing the value will immediately affect all instances of this skeleton.
Note: When you want to precisely match e.g. 32px of artwork to 1 game unit (and the attachment images have not been scaled in Spine), you can set this
Scale
parameter to1/px_per_unit
. So for32px/unit
you would setScale
to1/32 = 0.03125
. -
SkeletonData Modifiers. Provide a way for users to add additional processing to skeleton data assets after loading from a
.json
or.skel.bytes
file has been completed. Please consult section SkeletonData Modifier Assets below for additional information. -
Blend Modes - Upgrade. Upgrades an obsolete
BlendModeMaterialAsset
to the native Blend Mode Materials properties shown below. -
Blend Mode Materials. Skeleton slots with special blend modes require additional materials. These materials are setup automatically upon import, unless a
BlendModeMaterialAsset
is in use with older Unity and spine-unity versions. It is recommended to upgrade an assignedBlendModeMaterialAsset
via theBlend Modes - Upgrade
button above, as it prevents problems with newer Unity versions. You can customize material templates for each blend mode in the Spine Preferences.- Apply Additive Material. When enabled, slots with
Additive
blend mode will also have materials generated for them. Enable this parameter when using Straight alpha workflow. It is not necessary when using PMA workflow asNormal
andAdditive
slots can be drawn with the same PMA material. - Additive Materials, Multiply Materials, Screen Materials. These lists show the currently used blend mode materials for each blend mode.
- Apply Additive Material. When enabled, slots with
Atlas
Atlas references are used by the skeleton to resolve the exported image name references to the respective image areas for rendering.
Upon import the Atlas Assets
array is automatically populated with one entry per atlas asset (ending with _Atlas).
In case spine-unity failed to automatically assign all required atlas assets, you can change the Atlas Assets
Size
to the desired amount of atlas assets and manually assign the required atlas assets to Element0
- ElementN
.
Mix Settings
The skeleton data asset allows you to specify animation mix times.
Default Mix Duration
allows you to enter the default mix time, in seconds.
You can define mix times for two specific animations by clicking the Add Custom Mix
button in the Custom Mix Durations
section of the asset and setting specific mix durations, overriding the default mix duration value above.
Components using the skeleton data asset, like the skeleton animation component, use these mix times when playing back animations.
Preview
The Preview section for a skeleton data asset allows you to inspect all bones, slots, animations, skins, and events contained in the asset.
You can playback animations via the play buttons to the left of each animation and view a live update of the respective slots via Show Attachments
in the Slots
section. The timeline bar shows all events as purple markers. Hover over the markers while playing to display the event name.
Use the Create Animation Reference Assets
button to generate reference assets for all animations of the skeleton. An AnimationReferenceAsset
acts as a Unity asset referencing a single Spine.Animation
and can be assigned to component properties in the Inspector.
Skeleton Mecanim
In case you want to use Unity's Mecanim animation system instead of Spine's default animation system, you can generate and assign a Mecanim controller via Generate Mecanim Controller
.
Skeleton Baking
Note: Baking is a specialized tool and is not the recommended way of using Skeletons in spine-unity! It is not used for SkeletonMecanim, SkeletonAnimation or SkeletonGraphic (UI) components! It will instead bake a Skeleton down to a less flexible Prefab with a fixed hierarchy of
Transforms
withMeshRenderers
and compatible animation clips. A lot of Spine's features don't exist in Unity's Animation system so they can't be translated and are ignored in the process.
To open the Skeleton Baking Window
, click on the gear icon at the top right of the SkeletonDataAsset
Inspector and choose Skeleton Baking
.
A detailled list of supported and unsupported features can be found here in SkeletonBaker.cs.
Note: Baking is not using the recently added Unity 2D animation system but the previously existing 3D
MeshRenderer
based system.
Texture Atlas Asset
The texture atlas asset contains information about the images used by your skeleton, namely on what texture atlas page an image is stored, as well as its UV texture coordinates on the texture atlas page.
You can view the material of the texture atlas pages by double clicking the material asset in the Materials
array.
Note: You can modify the materials and textures referenced by the texture atlas asset. When modifying textures, make sure the UV texture coordinates stay valid.
The Set Mipmap Bias to -0.5
button is intended for advanced users and can be used to compensate for blurry appearance when Generate Mip Maps
is enabled on an atlas texture.
You can generate sprites for each image element of an atlas by pressing the Apply Regions as Texture Sprite Slices
button. The generated sprites reference areas of the texture atlas image (png
file) and can be used as any Unity sprite asset.
SkeletonData Modifier Assets
SkeletonData modifier assets provide a way for users to add additional processing to skeleton data assets after loading from a .json
or .skel.bytes
file has been completed.
SkeletonDataAsset's Inspector provides a Skeleton Data Modifiers
list you can add assets to.
Included SkeletonData Modifiers - BlendModeMaterialsAsset (obsolete)
Note: spine-unity now provides native support for slot blend modes
Additive
,Multiply
andScreen
at eachSkeletonDataAsset
, with automatic setup at newly imported skeleton assets.BlendModeMaterialAssets
are now obsolete and replaced by the native properties atSkeletonDataAsset
. TheSkeletonDataAsset
Inspector provides a newBlend Modes - Upgrade
button to upgrade an obsoleteBlendModeMaterialAsset
to the native blend modes properties. This upgrade will be performed automatically on imported and re-imported assets in Unity 2020.1 and newer to prevent reportedBlendModeMaterialAsset
issues in these Unity versions. spine-unity 4.0 and newer will automatically perform this upgrade regardless of the Unity version.
BlendModeMaterialsAsset
is a SkeletonData modifier asset class included in spine-unity. It holds references to materials that can be used to render attachments within slots that have the Additive
, Multiply
and Screen
blend modes assigned to them in the Spine editor.
The Material references stored in BlendModeMaterials assets are used as templates to generate new Materials that use the appropriate texture needed by the loaded attachments.
The spine-unity runtime comes packaged with a ready-to-use BlendModeMaterialsAsset
named Default BlendModeMaterials
. Using this included asset allows the attachments in slots with special blend modes to use the included default Multiply
and Screen
shaders: Spine/Blend Modes/Skeleton PMA Multiply
and Spine/Blend Modes/Skeleton PMA Screen
.
If you need to use different Materials or shaders or Materials with different settings, you can create new BlendModeMaterialsAsset
s using Create -> Spine -> SkeletonData Modifiers -> Blend Mode Materials
. Then assign your Material templates to the created asset.
Writing a custom SkeletonDataModifierAsset class
You can write your own custom SkeletonDataModifierAsset
class to add additional processing to skeleton data assets after loading from a .json
or .skel.bytes
file. SkeletonDataModifierAsset
is an abstract ScriptableObject
class where you can derive your own classes from.
-
Create a new class derived from
SkeletonDataModifierAsset
and implement thevoid Apply (SkeletonData skeletonData)
method. Add theCreateAssetMenu
class attribute to list an entry for your class in theAsset -> Create
menu.C#
[[CreateAssetMenu(menuName = "TopMenu/Submenu/SubSubmenu", order = 200)]
public class Blend Mode Materials Asset : Skeleton Data Modifier Asset {public override void Apply (Skeleton Data skeletonData) {
...
}
} -
Create an instance of your new class by selecting your desired folder in the Project panel and selecting your newly created
Asset -> Create
menu entry. Assign the created asset at an element of theSkeleton Data Modifiers
list of your SkeletonData asset.
Apply(skeletonData)
will be called after loading data from the .json
or .skel.bytes
file has been completed.
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 above.
Adding a Skeleton to a Scene
To quickly display a Spine skeleton in your Unity project:
- Import the skeleton data and texture atlas as described above.
- 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:
- Create a new empty GameObject via
GameObject -> Create Empty
.- Select the GameObject and in the inspector click
Add Component
, then selectSkeletonAnimation
. This will automatically add the additionalMeshRenderer
andMeshFilter
components as well.- 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 thandefault
.
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:
- SkeletonAnimation - Uses Spine's custom animation and event system, providing highest customizability. Renders using a
MeshRenderer
, interacting with masks such asSpriteMask
like a Unity sprite. The recommended way of using a Spine skeleton in Unity. - SkeletonGraphic (UI) - For use as UI element together with a Unity
Canvas
. Renders and interacts with UI masks such asRectMask2D
like the built-in Unity UI elements. Animation and event behaviour is identical to SkeletonAnimation. - 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
Skeleton Animation instance = Skeleton Animation.NewSkeletonAnimationGameObject(skeletonDataAsset);
// instantiating a SkeletonGraphic GameObject from a SkeletonDataAsset
Skeleton Graphic instance
= Skeleton Graphic.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)
Spine Atlas Asset runtimeAtlasAsset
= Spine Atlas Asset.CreateRuntimeInstance(atlasTxt, textures, materialPropertySource, true);
Skeleton Data Asset runtimeSkeletonDataAsset
= Skeleton Data Asset.CreateRuntimeInstance(skeletonJson, runtimeAtlasAsset, true);
// 3. Create SkeletonAnimation (needs a valid SkeletonDataAsset)
Skeleton Animation instance = Skeleton Animation.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
- Select the SkeletonAnimation GameObject
- Assign a _SkeletonData asset at the
SkeletonData Asset
property in the Inspector.
Setting Initial Skin and Animation
The SkeletonAnimation Inspector exposes the following parameters
- 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. - Animation Name. This animation will be played upon start.
- Loop. Defines whether the initial animation shall be looped or played only once.
- Time Scale. You can set the time scale to slow down or speed up playback of animations.
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.
- 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 toDontSaveInEditor
), but at the cost of references to theMeshFilter
by other components being lost. - 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 modeBlend One OneMinusSrcAlpha
. Disable this parameter for normal shaders with regular blend modeBlend SrcAlpha OneMinusSrcAlpha
. When disabled, it prevents single-batch rendering of additive slots and may increase the number of draw calls. - Tint Black (!). Adds black tint vertex data to the mesh. Black tinting requires that the shader interpret 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, theSpine/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 theSpine/Sprite
shaders can be configured to assume aFixed 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.
- 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. And then the new frame is applied to the Skeleton as a new pose.
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 callskeleton.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. -
OnMeshAndMaterialsUpdated
is raised at the end ofLateUpdate()
after the Mesh and all materials have been updated.
C#
// your delegate method
void AfterUpdateComplete (I Skeleton Animation anim) {
// this is called after animation updates have been completed.
}
// register your delegate method
void Start() {
skeletonAnimation.Update Complete -= After Update Complete;
skeletonAnimation.Update Complete += After Update Complete;
}
As an alternative, you can change Script Execution Order to run after SkeletonAnimation's Update method.
For more information on Unity's MonoBehaviour Lifecycle, see: docs.unity3d.com/Manual/ExecutionOrder
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 Your Component : Mono Behaviour {
Skeleton Animation skeletonAnimation;
Spine.Animation State animationState;
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.Animation State;
}
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
[Spine Slot] public string slotProperty = "slotName";
[Spine Attachment] 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.
C#
skeleton.SetToSetupPose();
skeleton.SetBonesToSetupPose();
skeleton.SetSlotsToSetupPose();
Setting Skins
A Spine skeleton may have multiple skins that define which attachment go on which slot. The skeleton component provides a simple way to switch between skins.
C#
bool success = skeletonAnimation.Skeleton.SetSkin("skinName");
C#
// using properties
[Spine Skin] public string skinProperty = "skinName";
...
bool success = skeletonAnimation.Skeleton.SetSkin(skinProperty);
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();
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.Attachment Tools;
// Create a repacked skin.
Skin repackedSkin = collectedSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.Skeleton Data Asset.atlasAssets[0].Primary Material, out runtimeMaterial, out runtimeAtlas);
collectedSkin.Clear();
// Use the repacked skin.
skeletonAnimation.Skeleton.Skin = repackedSkin;
skeletonAnimation.Skeleton.SetSlotsToSetupPose();
skeletonAnimation.Animation State.Apply(skeletonAnimation.Skeleton);
// You can optionally clear the cache after multiple repack operations.
Atlas Utilities.ClearCache();
Important Note: If repacking fails or creates unexpected results, it is most likely due to any of the following causes:
- 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.- Compression is enabled: Depending on the platform, ensure that the source texture has Texture import setting
Compression
set toNone
instead ofNormal Quality
.- 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.
- 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 hasNon-Power of Two
set toNone
.
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;
Texture2 D runtimeAtlas;
Texture2 D[] additionalOutputTextures = null;
int[] additionalTexturePropertyIDsToCopy = new int[] { Shader.PropertyToID("_BumpMap") };
Skin repackedSkin = prevSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.Skeleton Data Asset.atlasAssets[0].Primary Material, out runtimeMaterial, out runtimeAtlas,
additionalTexturePropertyIDsToCopy : additionalTexturePropertyIDsToCopy, additionalOutputTextures : additionalOutputTextures);
// Use the repacked skin.
skeletonAnimation.Skeleton.Skin = repackedSkin;
skeletonAnimation.Skeleton.SetSlotsToSetupPose();
skeletonAnimation.Animation State.Apply(skeletonAnimation.Skeleton);
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.
Changing Scale 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.Scale X < 0;
skeleton.Scale X = -1;
bool isFlippedY = skeleton.Scale Y < 0;
skeleton.Scale Y = -1;
skeleton.Scale X = -skeleton.Scale X; // toggle flip x state
Getting and Setting Bone Transforms Manually
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, 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.5 f;
Setting Animations
To set an animation, provide the track index, animation name and whether to loop the animation.
C#
Track Entry entry = skeletonAnimation.Animation State.SetAnimation(trackIndex, "walk", true);
C#
// using properties
[Spine Animation] public string animationProperty = "walk";
...
Track Entry entry = skeletonAnimation.Animation State.SetAnimation(trackIndex, animationProperty, true);
As an alternative, you can use an AnimationReferenceAsset instead of a string as parameter.
C#
// using AnimationReferenceAsset
public Animation Reference Asset animationReferenceAsset; // assign a generated AnimationReferenceAsset to this property
...
Track Entry entry = skeletonAnimation.Animation State.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#
Track Entry entry = skeletonAnimation.Animation State.AddAnimation(trackIndex, "run", true, 2);
C#
// using properties
[Spine Animation] public string animationProperty = "run";
...
Track Entry entry = skeletonAnimation.Animation State.AddAnimation(trackIndex, animationProperty, true, 2);
Setting and Queueing Empty Animations, Clearing Tracks
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#
Track Entry entry = skeletonAnimation.Animation State.SetEmptyAnimation(trackIndex, mixDuration);
entry = skeletonAnimation.Animation State.AddEmptyAnimation(trackIndex, mixDuration, delay);
skeletonAnimation.Animation State.ClearTrack(trackIndex);
skeletonAnimation.Animation State.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#
Track Entry entry = ...
entry.Event Threshold = 2;
float trackEnd = entry.Track End;
Processing AnimationState Events
While animations are played back by the underlying AnimationState
, various events will be emitted that notify listeners that
- An animation started.
- An animation was interrupted, e.g. by clearing a track or setting a new animation.
- An animation was completed without interruption, which may occur multiple times if looped.
- An animation has ended.
- An animation and its corresponding
TrackEntry
have been disposed. - A user defined event was fired.
Note: When setting a new animation which interrupts a previous one, no
complete
event will be raised butinterrupt
andend
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#
Skeleton Animation skeletonAnimation;
Spine.Animation State animationState;
void Awake () {
skeletonAnimation = GetComponent<SkeletonAnimation>();
animationState = skeletonAnimation.Animation State;
// registering for events raised by any animation
animationState.Start += On Spine Animation Start;
animationState.Interrupt += On Spine Animation Interrupt;
animationState.End += On Spine Animation End;
animationState.Dispose += On Spine Animation Dispose;
animationState.Complete += On Spine Animation Complete;
animationState.Event += On User Defined Event;
// registering for events raised by a single animation track entry
Spine.Track Entry trackEntry = animationState.SetAnimation(trackIndex, "walk", true);
trackEntry.Start += On Spine Animation Start;
trackEntry.Interrupt += On Spine Animation Interrupt;
trackEntry.End += On Spine Animation End;
trackEntry.Dispose += On Spine Animation Dispose;
trackEntry.Complete += On Spine Animation Complete;
trackEntry.Event += On User Defined Event;
}
public void OnSpineAnimationStart(Track Entry trackEntry) {
// Add your implementation code here to react to start events
}
public void OnSpineAnimationInterrupt(Track Entry trackEntry) {
// Add your implementation code here to react to interrupt events
}
public void OnSpineAnimationEnd(Track Entry trackEntry) {
// Add your implementation code here to react to end events
}
public void OnSpineAnimationDispose(Track Entry trackEntry) {
// Add your implementation code here to react to dispose events
}
public void OnSpineAnimationComplete(Track Entry trackEntry) {
// Add your implementation code here to react to complete events
}
string targetEventName = "targetEvent";
string targetEventNameInFolder = "eventFolderName/targetEvent";
public void OnUserDefinedEvent(Spine.Track Entry 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.Event Data targetEventData;
void Start () {
targetEventData = skeletonAnimation.Skeleton.Data.FindEvent(targetEventName);
}
public void OnUserDefinedEvent(Spine.Track Entry 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.
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:
-
WaitForSpineAnimation. Waits until a
Spine.TrackEntry
raises one of the specified events.C#
var track = skeletonAnimation.state.SetAnimation(0, "interruptible", false);
var completeOrEnd = Wait For Spine Animation.Animation Event Types.Complete |
Wait For Spine Animation.Animation Event Types.End;
yield return new WaitForSpineAnimation(track, completeOrEnd); -
WaitForSpineAnimationComplete. Waits until a
Spine.TrackEntry
raises aComplete
event.C#
var track = skeletonAnimation.state.SetAnimation(0, "talk", false);
yield return new WaitForSpineAnimationComplete(track); -
WaitForSpineAnimationEnd. Waits until a
Spine.TrackEntry
raises anEnd
event.C#
var track = skeletonAnimation.state.SetAnimation(0, "talk", false);
yield return new WaitForSpineAnimationEnd(track); -
WaitForSpineEvent. Waits until a
Spine.AnimationState
raises a user-definedSpine.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.Event Data 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#
[Spine Bone] public string bone;
[Spine Slot] public string slot;
[Spine Attachment] public string attachment;
[Spine Skin] public string skin;
[Spine Animation] public string animation;
[Spine Event] public string event;
[Spine Ik Constraint] public string ikConstraint;
[Spine Transform Constraint] public string transformConstraint;
[Spine Path Constraint] 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 instead of the Spine animation system. As the SkeletonAnimation component, it allows you to add a Spine skeleton to a GameObject, animate it, react to animation events, and so on. 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.AttachmentThreshold
and similar mix threshold functionality is not available forSkeletonMecanim
.
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 precedingjump
animation. Assumingjump
ends with bonesbone1
andbone2
keyed in non-setup-pose location, you have to add keys (in setup pose or any custom pose) at the first frame of theidle
animation forbone1
andbone2
to properly mix out thejump
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!
Parameters for 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, aMix Modes
section is shown below allowing you to specify aMixMode
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
andOverride
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 whenAuto 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.
- Mix Next (recommended for
-
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:
- Starts with
current state last frame
(or other modifications this frame prior to SkeletonMecanim's update). - Apply
setup pose
:- When
Auto Reset
is enabled, thesetup pose
replaces thecurrent state last frame
. - When
Auto Reset
is disabled,setup pose
is not part of the mix.
- When
- Apply
previous clip pose
:- When mode is set to
Always Mix
, theprevious clip pose
is mixed with the current state (so mixed withsetup pose
whenAuto Reset
is enabled). - When set to
Hard
orMix Next
, theprevious clip pose
is applied with full weight, overriding the current state (thus overridingsetup pose
).
- When mode is set to
- Apply
new clip pose
:- When mode is set to
Always Mix
orMix Next
, thenew clip pose
is mixed with the current state. So atAlways Mix
withAuto Reset
enabled it is a mix ofsetup pose
,previous clip pose
andnew clip pose
. - When mode is set to
Hard
, thenew clip pose
is applied with full weight, overriding all previously applied poses.
- When mode is set to
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. |
SkeletonMecanim 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 yourSkeletonMecanim
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 Your Component Receiving Events : Mono Behaviour {
// 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 enableAdvanced - Multiple CanvasRenderers
at theSkeletonGraphic
component Inspector to generate a childCanvasRenderer
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.
Match RectTransform bounds for 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:
-
Unscaled Time. When set to
true
, updates will be performed according to Time.unscaledDeltaTime instead of Time.deltaTime. This is useful to animated UI elements independently of slow-motion effects. -
Freeze. When set to
true
, theSkeletonGraphic
will no longer be updated. -
Match RectTransform with Mesh You can make a
SkeletonGraphic
's RectTransform fit its current pose's dimensions by clicking theMatch
button. It is important that the RectTransform bounds are not smaller than the mesh, otherwise e.g. aRectMask2D
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.
-
Advanced
-
Use Clipping. When set to
false
, any Spine clipping attachments will be ignored. -
Canvas Group Tint Black. Only enable when using the
SkeletonGraphic Tint Black
shader. Has no effect whenTint Black
is disabled. Enable when usingAdditive
blend mode at a slot ofSkeletonGraphic
under aCanvasGroup
. When enabled,Additive
alpha value is stored atuv2.g
instead ofcolor.a
to captureCanvasGroup
modifyingcolor.a
. -
Multiple CanvasRenderers. When set to
true
,SkeletonGraphic
no longer uses a singleCanvasRenderer
but automatically creates the required number of childCanvasRenderer
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 otherCanvasRenderer
compatible materials here. -
Select
Assign Default
to assign the default blend mode materialsSkeletonGraphicAdditive
,SkeletonGraphicMultiply
andSkeletonGraphicScreen
.Note: Be sure to have a proper setup of
Blend Mode Materials
at theSkeletonDataAsset
, as theSkeletonGraphic
blend mode material assignment relies on theSkeletonDataAsset's
materials.Additive Material
is ignored whenPMA Vertex Colors
is enabled.
-
-
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 withSkeletonGraphic
. -
Enable Separation. Render separation can be enabled directly in this Inspector section, it does not require any additional components (like
SkeletonRenderSeparator
orSkeletonPartsRenderer
forSkeletonRenderer
components). When enabled, additional separation part GameObjects will be created automatically, andCanvasRenderer
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 yourCanvas
. -
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.
-
Example Scenes
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.
Utility Components
SkeletonRootMotion
spine-unity supports root motion on all three Spine skeleton components. The SkeletonRootMotion
component can be attached to SkeletonAnimation and SkeletonGraphic (UI) GameObjects, while a separate SkeletonMecanimRootMotion component is provided for SkeletonMecanim. Attaching this root motion component is similar to enabling the Apply Root Motion
parameter at the Unity Mecanim Animator
component. When enabled, the character's position is driven by the animation according to the movement of the selected Root Motion Bone
.
Note: There is a SkeletonMecanimRootMotion component provided for SkeletonMecanim objects.
SkeletonRootMotion
will fail when used onSkeletonAnimation
orSkeletonGraphic (UI)
components.
Parameters
- Root Motion Bone. The target bone whose movement is used as root motion.
- X. When enabled, movement along the local X axis is applied as root motion.
- Y. When enabled, movement along the local Y axis is applied as root motion.
- Root Motion Scale (X). Scale applied to the horizontal root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired distance.
- Root Motion Scale (Y) Scale applied to the vertical root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired height.
- Animation Tracks. Allows you to specify which animation tracks shall be included in root motion calculations.
Optional Parameters
- Rigidbody2D. When a
Rigidbody2D
is assigned, movement is applied via physics to the givenRigidbody2D
instead of theTransform
component. - Rigidbody. When a
Rigidbody
is assigned, movement is applied via physics to the givenRigidbody
instead of theTransform
component.
Note: The
SkeletonRootMotion
class providesAdjustRootMotionToDistance()
and other methods to allow for easy delta compensation. Delta compensation can be used to e.g. stretch a jump to a given distance. Root motion can be adjusted at the start of an animation or every frame viaskeletonRootMotion.AdjustRootMotionToDistance(targetPosition - transform.position, trackIndex);
.
SkeletonMecanimRootMotion
This component is a variant of the SkeletonRootMotion component to be used with SkeletonMecanim components.
The SkeletonMecanimRootMotion
component is automatically added to your skeleton GameObject when the Apply Root Motion
parameter at the Unity Mecanim Animator
is enabled. To remove the SkeletonMecanimRootMotion
component you have to ensure to disable the Animator's Apply Root Motion
parameter first.
Parameters
- Root Motion Bone. The target bone whose movement is used as root motion.
- X. When enabled, movement along the local X axis is applied as root motion.
- Y. When enabled, movement along the local Y axis is applied as root motion.
- Root Motion Scale (X). Scale applied to the horizontal root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired distance.
- Root Motion Scale (Y) Scale applied to the vertical root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired height.
- Mecanim Layers. Allows you to specify which Mecanim layers shall be included in root motion calculations.
Optional Parameters
- Rigidbody2D. When a
Rigidbody2D
is assigned, movement is applied via physics to the givenRigidbody2D
instead of theTransform
component. - Rigidbody. When a
Rigidbody
is assigned, movement is applied via physics to the givenRigidbody
instead of theTransform
component.
Note: The
SkeletonMecanimRootMotion
class providesAdjustRootMotionToDistance()
and other methods to allow for easy delta compensation. Delta compensation can be used to e.g. stretch a jump to a given distance. Root motion can be adjusted at the start of an animation or every frame viaskeletonRootMotion.AdjustRootMotionToDistance(targetPosition - transform.position, trackIndex);
.
BoneFollower
This component references a bone of a SkeletonAnimation component and sets its own transform to that of the bone on every Update
.
Note: There is a BoneFollowerGraphic component provided for SkeletonGraphic objects.
In contrast to the SkeletonUtilityBone component a BoneFollower
can be used as a single isolated GameObject without any parent bone objects.
Use this to let objects like particle systems follow a specific bone on the skeleton.
You can examine the example scene Spine Examples/Getting Started/4 Object Oriented Sample on how to set up a BoneFollower
component.
BoneFollowerGraphic
This component is a variant of the Bone Follower component to be used with SkeletonGraphic components.
In contrast to the SkeletonUtilityBone component a BoneFollowerGraphic
can be used as a single isolated GameObject without any parent bone objects.
Use this to let objects like particle systems follow a specific bone on the skeleton.
You can examine the example scene Spine Examples/Getting Started/6 Skeleton Graphic on how to set up a BoneFollowerGraphic
component.
PointFollower
This component is similar to the Bone Follower component but follows a PointAttachment instead of a bone.
In contrast to the SkeletonUtilityBone component a PointFollower
can be used as a single isolated GameObject without any parent bone objects.
BoundingBoxFollower
This component is used to match a Bounding Box at a skeleton's slot. It extracts the shape and assigns it at a PolygonCollider2D
and enables or disables it every frame to match the current animation.
Note: The bone's position is not automatically followed, which is why it is typically used together with a
BoneFollower
component. You can use theAdd Bone Follower
button in theBoundingBoxFollower
inspector to create and setup aBoneFollower
component.
Note: Vertex deformation animation (moving vertices of a Bounding Box over time in an animation) is not followed along, it only covers the initial shape.
See Bone Follower for further information.
SkeletonUtilityBone
Sometimes you may want to modify bone positions programmatically at runtime to react to physics or user input.
The SkeletonUtilityBone component provides a convenient interface to let GameObjects follow a bone position, override a bone position manually or via 2D and 3D physics. It can be configured to either follow the local bone position or override it on every Update
. When set to Override
, the component will set the bone position before the SkeletonAnimation component updates the world transforms.
Important Note: A
SkeletonUtilityBone
uses local transform values. It relies on a hierarchy ofSkeletonUtilityBone
GameObjects that mirrors the skeleton's bone hierarchy. The recommended way to quickly create aSkeletonUtilityBone
hierarchy is via theSkeletonUtility
component described below.
The SkeletonUtilityBone
Inspector also provides an interface to create additional child bones (selectively or recursively) or create a 2D and 3D hinge chain.
Once your hierarchy of SkeletonUtilityBones
is created, the Hierarchy panel shows different icons next to a SkeletonUtilityBone
GameObject depending on whether it is set to
Example Use Case
Use a SkeletonUtilityBone
in Override
mode for use cases such as letting the user drag a bone of the skeleton around.
In case you need a GameObject to follow only a single bone position, you can use the BoneFollower component instead to save resources.
Example Scene
You can find an example scene that demonstrates usage of SkeletonUtilityBone
at Spine Examples/Other Examples/SkeletonUtility Animated Physics
. It shows how some SkeletonUtilityBones
nodes are configured to Follow
bone positions to be the necessary hierarchial parents for the Override
nodes.
Create 2D and 3D Hinge Chains for Physics
You may want to add physics to the cape of your character, have it drag heavy objects around or swing a morning-star. The spine-unity runtime allows you to generate a physics rig of HingeJoint or HingeJoint2D elements from an existing SkeletonUtilityBone hierarchy (see Creating a Hierarchy of SkeletonUtilityBones).
Select the first SkeletonUtilityBone
chain element and in the Inspector choose Create 3D Hinge Chain
or Create 2D Hinge Chain
to generate the physics rig. The selected element and all its SkeletonUtilityBone
children are turned into a hinge chain. You can then adjust the Rigidbody's drag and mass parameters to tweak the result. Raising the drag value will make the Rigidbody move slower and create the effect of being heavy or interact with air.
Note that the chain root node is no longer parented to bones of the skeleton, but placed at the top hierarchy level of the scene. This is a requirement in Unity to have momentum applied properly. Do not reparent the chain root to bones of your skeleton, or chain elements will no longer be affected by skeleton movement!
3D hinge chains
- Create a SkeletonUtilityBone hierarchy as usual.
- Select the first chain element in the Scene panel and in the Inspector choose
Create 3D Hinge Chain
to create the 3D hinge chain rig. - This will remove the chain GameObjects from the previous parent (
cape-root
in the example) and place a newHingeChain Parent
GameObject at the top level of the scene. As mentioned above, do not reparent this GameObject to the skeleton! - Adjust chain elements Rigidbody drag and mass parameters to tweak the result.
When the skeleton is flipped, the HingeChain Parent
GameObject will automatically be rotated by 180 degrees to adjust the hinge chain to the flipped bone locations.
2D hinge chains
- Create a SkeletonUtilityBone hierarchy as usual.
- Select the first chain element in the Scene panel and in the Inspector choose
Create 2D Hinge Chain
to create the 2D hinge chain rig. - This will remove the chain GameObjects from the previous parent (
cape-root
in the example) and place a newHingeChain Parent
GameObject at the top level of the scene. As mentioned above, do not reparent this GameObject to the skeleton! - Adjust chain elements Rigidbody2D drag and mass parameters to tweak the result.
Note that this GameObject contains two child objects, named Hinge Chain
and Hinge Chain FlippedX
. When the skeleton is flipped, these GameObjects will automatically be activated and deactivated to enable the respective hinge chain.
SkeletonUtility
Creating a Hierarchy of SkeletonUtilityBones
The SkeletonUtility
component offers a quick way to create a hierarchy of SkeletonUtilityBone
GameObjects mirroring the bone hierarchy of the skeleton.
To create a SkeletonUtility
component, select your SkeletonAnimation component and in the Inspector unfold the Advanced
section and hit Add Skeleton Utility
. Once created, the Add Skeleton Utility
button will disappear and SkeletonUtility
component is added to your GameObject.
The SkeletonUtility
component provides a Spawn Hierarchy
button with the following options presented on click:
-
Follow all bones
CreatesSkeletonUtilityBone
GameObjects for all bones in the hierarchy, set to modeFollow
-
Follow (Root Only)
Creates only the rootSkeletonUtilityBone
GameObject, set to modeFollow
-
Override all bones
CreatesSkeletonUtilityBone
GameObjects for all bones in the hierarchy, set to modeOverride
-
Override (Root Only)
Creates only the rootSkeletonUtilityBone
GameObject, set to modeOverride
EachSkeletonUtilityBone
can then be configured to override bone positions of a skeleton where necessary.
Note: You can add additional
SkeletonUtilityBone
GameObjects via the inspector of aSkeletonUtilityBone
later, theSpawn Hierarchy
functionality serves as a rough starting point. You can also delete unneededSkeletonUtilityBone
GameObjects to save resources. Just remember you need to keep their parents intact, so do not delete GameObjects in the middle of a hierarchy-chain or change their parents.
SkeletonUtilityConstraint
C#
Base class to derive skeleton utility constraint subclasses from. It automatically registers itself at the parent SkeletonUtility
and will be updated accordingly.
See example constraint classes SkeletonUtilityGroundConstraint
and SkeletonUtilityEyeConstraint
for how to write your own constraint classes.
Example Scenes
The spine-unity runtime comes with example scenes that demonstrate the above constraints. You can find them in Spine Examples/Other Examples/SkeletonUtility GroundConstraint
and Spine Examples/Other Examples/SkeletonUtility Eyes
.
SkeletonRendererCustomMaterials
You may want to override materials for a specific Skeleton instance or even only at certain slots. This component provides an inspector interface to assign custom material overrides for SkeletonRenderer, including subclasses SkeletonAnimation and SkeletonMecanim.
You can right-click on a SkeletonRenderer (or subclasses SkeletonAnimation and SkeletonMecanim) and select Add Basic Serialized Custom Materials
to add this component to the renderer. Add entries to the Custom Slot Materials
array to override materials at certain slots or to the Custom Material Overrides
array to replace one material with another for the whole skeleton. Be sure to uncheck Override Disabled
to enable the respective material overrides.
Note: This component is not intended to be interfaced through code. To dynamically set materials for your SkeletonRenderer through code, you can directly access
SkeletonRenderer.CustomMaterialOverride
for material array overrides andSkeletonRenderer.CustomSlotMaterials
for slot material overrides.
SkeletonGraphicCustomMaterials
A variant of SkeletonRendererCustomMaterials for SkeletonGraphic. This component provides an inspector interface to assign custom material and texture overrides for SkeletonGraphic.
You can right-click on a SkeletonGraphic and select Add Basic Serialized Custom Materials
to add this component to the GameObject. Add entries to the Custom Texture Overrides
array to replace one texture with another for the whole skeleton. Add entries to the Custom Material Overrides
array to replace the used material at an original texture (before replacement) with another material. Be sure to check Override Enabled
to enable the respective texture or material overrides.
Note: This component is not intended to be interfaced through code. To dynamically set materials for your SkeletonGraphic through code, you can directly access
SkeletonGraphic.CustomMaterialOverride
for material array overrides andSkeletonGraphic.CustomTextureOverride
for texture overrides.
SkeletonRenderSeparator
You may want to display other GameObjects between parts of your character, e.g. to let your character run into a tree and display one leg in front and one behind the trunk. The SkeletonRenderSeparator
component allows you to split your SkeletonRenderer (or subclass SkeletonAnimation and SkeletonMecanim) into two or more SkeletonPartsRenderers
with customizable layer order.
Note: The SkeletonGraphic component provides render separation functionality directly at the
SkeletonGraphic
Inspector in theAdvanced
section, it does not require any additional components.
Note: Normally, Spine renderer components will use a single renderer to display the whole mesh of a skeleton. This unfortunately prevents you from inserting other
UnityEngine.Renderers
(SpriteRenderer
,MeshRenderer
,ParticleSystem
, etc.) between its parts.
Setup
-
Make sure you know your Skeleton's draw order. Find out which slot you want to use to separate your Skeleton's render into parts. For convenience, label this slot clearly before exporting your Skeleton.
-
Add the SkeletonRenderSeparator component Select your Spine GameObject. Right-click on your SkeletonAnimation or SkeletonRenderer in the inspector. Choose
Add Skeleton Render Separator
. This will add theSkeletonRenderSeparator
component to the GameObject.
-
Assign Separator Slots The inspector now shows a warning that the list of separators is empty. Setup separator slots by choosing the desired slot(s) under
Separator Slot Names
. You can add additional separator slots using the+
button.Note: This field is serialized at the SkeletonRenderer (or SkeletonAnimation and SkeletonMecanim subclass) component,
SkeletonRenderSeparator
just provides the interface for it. -
Add Parts Renderers The inspector now shows a warning that you don't have enough parts renderers.
Click on theAdd the missing renderers (n)
button to create the required GameObjects withSkeletonPartsRenderer
components. These GameObjects will be automatically assigned at theParts Renderers
list above.Note: The
SkeletonRenderSeparator
detects the currently required number of parts renderers,depending on the current draw order. If draw order is modified at runtime, it may happen that the renderer requires more parts renderers. In this case you may need to add one or two additional parts renderers manually by clicking theAdd Parts Renderer
button. -
Setup
Sorting Layer
andOrder in Layer
Each of theSkeletonPartsRenderers
provides aSorting Layer
andOrder in Layer
property in the inspector. You can now setup the sorting properties at eachSkeletonPartsRenderer
. Higher values will move the renderer to the front.
Note: The
SkeletonPartsRenderer
GameObjects don't have to be children of your Spine GameObject. TheSkeletonRenderSeparator
keeps references, so you can organize them however you need to.
Example Scene
You can find an example scene that demonstrates usage of SkeletonPartsRenderer
and SkeletonRenderSeparator
at Spine Examples/Other Examples/SkeletonRenderSeparator
.
C#
Enabling and Disabling
By default, SkeletonRenderSeparator
will disable the SkeletonRenderer and take over his mesh rendering task. Likewise, if you disable SkeletonRenderSeparator
, SkeletonRenderer will take over rendering again.
You can enable and disable a SkeletonRenderSeparator
as any component:
C#
skeletonRenderSeparator.enabled = true; // separation is enabled.
skeletonRenderSeparator.enabled = false; // separation is disabled.
Changing the separation point
The point of separation is not stored in SkeletonRenderSeparator
.
It is defined by the separator slots in SkeletonRenderer (or subclasses SkeletonAnimation and SkeletonMecanim). If you want to manipulate separator slots at runtime, you can access the list SkeletonRenderer.separatorSlots
and manipulate it as usual by calling Add
, Remove
or Clear
.
C#
Spine.Slot mySlot = skeletonAnimation.Skeleton.FindSlot("MY SPECIAL SLOT");
skeletonAnimation.separatorSlots.Clear();
skeletonAnimation.separatorSlots.Add(mySlot);
Adding a SkeletonRenderSeparator at runtime
You can use the static method SkeletonRenderSeparator.AddToSkeletonRenderer
to add and initialize a new SkeletonRenderSeparator
component.
C#
Skeleton Animation skeletonAnimation = GetComponent<SkeletonAnimation>();
skeletonAnimation.Separator Slots.Add(mySlot); // see above
// Add the SkeletonRenderSeparator.
Skeleton Render Separator skeletonRenderSeparator = Skeleton Render Separator.AddToSkeletonRenderer(skeletonAnimation);
By default, it will add the currently necessary SkeletonPartsRenderers
. It provides a number of optional arguments for advanced use cases, please see the code documentation.
Rendering
Shaders
The spine-unity runtime includes several different shaders. By default, the Spine/Skeleton
shader will be assigned at a newly imported skeleton Material. You can change the shader via the Material's Shader parameter as usual. Below you will find a list of included Spine shaders.
Important Note: Use only special
CanvasRenderer
compatible shaders withSkeletonGraphic
components. See SkeletonGraphic - Important Material Requirements for details.
Note: Deferred Shading rendering path is not yet supported by Spine shaders.
-
Spine/Skeleton (Default Shader)
Unlit transparent shader. Does not write to the z-buffer. -
Spine/Skeleton Graphic (Default shader for SkeletonGraphic)
Unlit transparent shader used by SkeletonGraphic. Does not write to the z-buffer. Does not supportAdditive
blend mode when used with aCanvasGroup
, when required useSpine/Skeleton Graphic Tint Black
instead. Limited to a single texture because of CanvasRenderer limitations. -
Spine/Skeleton Lit
Simple lit transparent shader, no normal map support. Does not write to the z-buffer. -
Spine/Skeleton Lit ZWrite
Simple lit transparent shader, no normal map support. Writes to the z-buffer. -
Spine/Skeleton Fill
Unlit transparent shader with customizable color overlay. Does not write to the z-buffer.
FillColor
determines the overlay color,FillPhase
the color overlay intensity. -
Spine/Skeleton Tint
Unlit transparent shader with customizable two-color tint, tinting dark colors separately from light colors, called tint black. Does not write to the z-buffer.The texture's lighter colors are tinted with
Tint Color
, the texture's darker colors withBlack Point
color. This allows a tinted texture to be brighter than its original color, compared to ordinary multiply color blending. When setting bothTint Color
andBlack Point
to the same color it will result in a solid color overlay. When settingTint Color
to black andBlack Point
to white, the texture color will be inverted. -
Spine/Skeleton Tint Black
Unlit transparent shader with Spine-animated per-slot tint black feature. Does not write to the z-buffer.
Spine provides a Tint Black feature for slots, allowing animated black tint.Required additional setup step (for tint color vertex data):
- Enable
Tint Black
in the SkeletonAnimation's inspector in theAdvanced
section:
- Enable
-
Spine/Skeleton Tint Black Additive
Unlit transparent shader with Spine-animated per-slot tint black feature. Uses additive blend mode. Does not write to the z-buffer. -
Spine/SkeletonGraphic Tint Black
Variant ofSpine/Skeleton Tint Black
shader for SkeletonGraphic. SupportsAdditive
blend mode when used with aCanvasGroup
.Required additional setup steps (for tint color vertex data):
- Enable
Tint Black
in the SkeletonAnimation's inspector in theAdvanced
section. - Set the Material of the SkeletonGraphic to the
SkeletonGraphicTintBlack
material located in folderSpine/Runtime/spine-unity/Materials
.
- Select the parent Canvas and under
Additional Shader Channels
enableTexCoord1
andTexCoord2
.
Required additional setup steps for
Additive
blend mode at aCanvasGroup
:- Enable
Canvas Group Tint Black
at the SkeletonGraphic inspector in theAdvanced
section. - Enable
CanvasGroup Compatible
at the shader.
- Enable
-
Spine/Sprite
Sophisticated configurable shaders, allowing for more advanced lighting than theSpine/Skeleton Lit
shader. You can find a demonstration of theSpine/Sprite/Vertex Lit
shader in the example sceneSpine Examples/Other Examples/Sprite Shaders
.- Spine/Sprite/Unlit
Unlit shader with configurable blend mode, overlay color, hue, saturation and brightness adjustments. Configurable to write to z-buffer. Fog support. - Spine/Sprite/Vertex Lit
Sophisticated vertex-lit shader with configurable blend mode.
Supports normal maps, secondary albedo, metallic and emission maps.
Configurable color ramp for cel-shaded look and rim lighting based on normals.
Configurable overlay color, hue, saturation and brightness adjustments.
Configurable to write to z-buffer. Fog support. - Spine/Sprite/Pixel Lit
Pixel-lit variant ofSpine/Sprite/Vertex Lit
shader. This shader always writes to the z-buffer (ZWrite
is enabled as it uses aForwardAdd
pass).
- Spine/Sprite/Unlit
-
Spine/Special
- Spine/Special/Skeleton Grayscale
Unlit transparent shader for grayscale rendering with customizable intensity. Does not write to the z-buffer. - Spine/Special/Skeleton Ghost
Special shader used by SkeletonGhost component for trail rendering.
- Spine/Special/Skeleton Grayscale
-
Spine/Blend Modes
Intended for slots that have blend modesAdditive
,Multiply
andScreen
assigned in the Spine editor. It is recommended to automatically assign blend mode materials on import via the provided BlendModeMaterials SkeletonData Modifier asset.- Spine/Blend Modes/Skeleton PMA Additive
Unlit transparent shader. Uses additive blend mode. Does not write to the z-buffer. - Spine/Blend Modes/Skeleton PMA Multiply
Unlit transparent shader. Uses multiply blend mode. Does not write to the z-buffer. - Spine/Blend Modes/Skeleton PMA Screen
Unlit transparent shader. Uses screen blend mode. Does not write to the z-buffer.
- Spine/Blend Modes/Skeleton PMA Additive
-
Spine/Outline
All shaders above provide anOutline
parameter which can be enabled to switch to the respectiveSpine/Outline
shader variant, drawing an additional colored outline around the skeleton. You can find a demonstration of theSpine/Outline
shaders in the example sceneSpine Examples/Other Examples/Outline Shaders
.- Spine/Outline/OutlineOnly-ZWrite A special two-pass shader rendering only the outline. Writes to the z-buffer for proper outline occlusion at overlapping attachments.
URP Shaders - Extension UPM Package
Universal Render Pipeline (URP) shaders are provided as a separate UPM (Unity Package Manager) package. See section Optional Extension UPM Packages on how to download and install this package and section Updating an Extension UPM Package on how to update it.
The URP Shaders UPM package provides shaders specifically built for Unity's Universal render pipeline, including 2D Renderer functionality.
Note: Do not use URP Shaders with
SkeletonGraphic
components. See SkeletonGraphic - Important Material Requirements for details.
Note: Deferred Rendering Path, which has recently been added to the Universal Render Pipeline, is not yet supported by Spine URP shaders.
Shaders for URP with 2D Renderer (do not use with URP (3D) Forward Renderer)
- Universal Render Pipeline/2D/Spine/Skeleton Lit
Universal 2D renderer variant of theSpine/Skeleton Lit
shader. - Universal Render Pipeline/2D/Spine/Sprite
Universal 2D renderer variant of theSpine/Sprite/Vertex Lit
andPixel Lit
shaders.
Shaders for URP with 3D Forward Renderer (do not use with URP 2D Renderer)
- Universal Render Pipeline/Spine/Skeleton
Universal variant of theSpine/Skeleton
shader. - Universal Render Pipeline/Spine/Skeleton Lit
Universal variant of theSpine/Skeleton Lit
shader. - Universal Render Pipeline/Spine/Sprite
Universal variant of theSpine/Sprite/Vertex Lit
andPixel Lit
shaders. - Universal Render Pipeline/Spine/Outline/Skeleton-OutlineOnly
Universal variant of theSpine/Outline
shaders. URP does not allow multiple passes per shader, so it requires a separate material. You might want to consider theRenderExistingMesh
component, as demonstrated in theOutline Shaders URP
example scene included in this package.
The shaders can be assigned to materials as usual and will respect your settings of the assigned UniversalRenderPipelineAsset
under Project Settings - Graphics
.
You can find a demonstration of the URP shaders in the example scene com.esotericsoftware.spine.URP-shaders-4.0/Examples/URP Shaders.unity
in the extracted package.
LWRP Shaders - Extension UPM Package
Lightweight Render Pipeline (LWRP) shaders are provided as a separate UPM (Unity Package Manager) package. See section Optional Extension UPM Packages on how to download and install this package and section Updating an Extension UPM Package on how to update it.
The LWRP Shaders UPM package provides shaders specifically built for Unity's lightweight render pipeline.
Note: Do not use LWRP Shaders with
SkeletonGraphic
components. See SkeletonGraphic - Important Material Requirements for details.
- Lightweight Render Pipeline/Spine/Skeleton
Lightweight variant of theSpine/Skeleton
shader. - Lightweight Render Pipeline/Spine/Skeleton Lit
Lightweight variant of theSpine/Skeleton Lit
shader. - Lightweight Render Pipeline/Spine/Sprite
Lightweight variant of theSpine/Sprite/Vertex Lit
andPixel Lit
shaders.
The shaders can be assigned to materials as usual and will respect your settings of the assigned LightweightRenderPipelineAsset
under Project Settings - Graphics
.
You can find a demonstration of the LWRP shaders in the example scene com.esotericsoftware.spine.lwrp-shaders-4.0/Examples/LWRP Shaders.unity
in the extracted package.
Shader Graph
Currently there are no official Shader Graph Spine shaders or shader nodes available. Note that when exporting your textures from Spine using Straight alpha settings, you should be able to use any non-Spine shader available. In case you want to replicate a feature that only the Spine shaders have to offer, please have a look at the forum for postings like these [1], [2]. If you have any questions, you can always start a new forum thread in the Unity subforum.
Amplify Shader Editor
While there is no officially provided shader template for the Amplify Shader Editor, user Hana
has kindly shared template code on the forum here.
Writing your own shaders
Please first familiarize with how to write custom shaders for Unity in general. Especially Tutorial: vertex and fragment programs provides a good overview, allowing you to more easily understand what the individual parts of spine-unity shaders are doing.
Starting from an existing spine-unity shader
It is highly recommended to start with a copy of an existing spine-unity shader. You can then gradually modify an already working shader to adjust it to achieve the desired effect. You can for example add additional color processing before returning the final color. The following code shows a short example on how to create a modified version of the SkeletonGraphic
shader extended by grayscale functionality:
Properties
{
_GrayIntensity("Intensity", Range(0, 1)) = 1 // this line was added to provide a Material property
[..]
}
sampler2D _MainTex;
float _GrayIntensity; // this parameter was added
..
fixed4 frag (Vertex Output I N) : S V_ Target
{
..
color.rgb = lerp(color.rgb, dot(color.rgb, float3(0.3, 0.59, 0.11)), _GrayIntensity); // this line was added
return color;
}
Caveats when using non-Spine shaders or visual shader editors
Be sure to consider the following differences between typical spine-unity shaders and other non-Spine shaders:
- Backface culling must be disabled by setting
Cull Off
when rendering any Spine skeletons. - Spine shaders typically don't need normals, therefore
Advanced - Add Normals
may need to be enabled at your component when using lit shaders. - Spine shaders typically don't need tangents, therefore
Advanced - Solve Tangents
may need to be enabled at your component when using normal maps. - Spine shaders use Premultiply Alpha textures by default. Either
a) export atlas textures as Straight alpha, or
b) change the blend mode of the shader to PMA blend modeBlend One OneMinusSrcAlpha
. - Spine vertex colors are typically PMA vertex colors. When using transparent or
Additive
Slots, you may either
a) change the blend mode of the shader to PMA blend modeBlend One OneMinusSrcAlpha
and use PMA atlas textures, or b) disableAdvanced - PMA Vertex Colors
at your component (not renderingAdditive
Slots then).
As always, general rules for UI and non-UI shaders apply:
- Do not use UI shaders on
SkeletonAnimation
orSkeletonMecanim
. - Do not use non-UI shaders on
SkeletonGraphic
.
Analysis of the Spine/Skeleton
shader
The following section provides an analysis of the Spine/Skeleton
shader. This shader is applied by default when a Material is generated upon importing your Spine texture atlas. The Spine/Skeleton
shader is fairly short and typical, and has the following characteristics:
- Premultiply Alpha (PMA) blending
- No depth buffer writing
- No lighting
- No backface culling
- No fog
- Uses vertex colors to tint the texture via multiply
- Optionally uses straight alpha instead of PMA textures
- Has a
"ShadowCaster"
pass so it can cast realtime shadows - Material Properties:
- _MainTex "Main Texture"
- _StraightAlphaInput "Straight Alpha Texture"
- _Cutoff "Shadow alpha cutoff"
- Advanced parameters:
- _StencilRef "Stencil Reference"
- _StencilComp "Stencil Comparison"
- Outline parameters (_OutlineWidth "Outline Width", etc.)
In detail:
-
Premultiply Alpha (PMA) blending
hlsl
Blend One One Minus Src Alpha
(Spine-Skeleton.shader:25)
Blending is defined as
result_rgba = frag_output_rgba * src_factor + framebuffer_rgba * dst_factor
.
The non-standardBlend One OneMinusSrcAlpha
PMA blend mode allows Slots that are set toAdditive
blend mode to be drawn in a single render pass withNormal
blend mode Slots. This is achieved by usingOne
atSrcFactor
in the above line (instead ofSrcAlpha
). This adds the unmodifiedfrag_output_rgba
value to theOneMinusSrcAlpha
weightedframebuffer_rgba
:
a) ForNormal
blending the fragment shader multipliesRGB
byA
and leavesA
as-is.
b) ForAdditive
blendingRGB
is not multiplied by alpha, andA
is set to0
, receivingresult_rgba = frag_output_rgba + (1-0) * framebuffer_rgba
.The
Normal
andAdditive
Slot blend modes are implicitly passed to the shader as vertex color when the Advanced -PMA Vertex Colors
is enabled at yourSkeletonRenderer
orSkeletonGraphic
Component:hlsl
struct Vertex Input {
float4 vertexColor : C O L O R
}(Spine-Skeleton.shader:47)
When multiplying the PMA vertex colors with the sampled PMA texture colors, Slot blend modes
Normal
orAdditive
are automatically applied:hlsl
return (texColor * i.vertexColor);
(Spine-Skeleton.shader:71)
So to support proper
Normal
andAdditive
PMA blend modes in your shader:- Define the blend function as
Blend One OneMinusSrcAlpha
- Multiply the texture color by the vertex color
- Enable Advanced -
PMA Vertex Colors
at the Component.
If you want to use a shader using standard blend mode
Blend SrcAlpha OneMinusSrcAlpha
and don't needAdditive
Slots, you need to make sure to export your used atlas textures from Spine as Straight alpha. - Define the blend function as
-
No depth buffer writing
(Spine-Skeleton.shader:24)
Not writing to the depth buffer is typical of an alpha-blended 2D sprite shader. Transparent objects will be drawn in back-to-front order according to your
Camera.transparencySortMode
instead of relying on the depth buffer for depth sorting.Spine/Skeleton
shares this characteristic with Unity's ownSprites/Default
shader.If you want to use a shader that has depth write enabled, be sure to set
Advanced - Z-Spacing
to a value other than0
at yourSkeletonRenderer
orSkeletonGraphic
Component to prevent Z-Fighting, especially if you have lighting applied. Note that using the depth buffer may cause unwanted results around semitransparent areas, including aliasing effects on edges. -
No lighting
TheSpine/Skeleton
shader is not affected by any Lights that are placed in the scene and will always be rendered in fulltexColor * i.vertexColor
intensity.In order to apply lighting in a shader it is recommended to start from a working lit shader and modify your own copy accordingly. Simply changing the line
Lighting Off
toLighting On
will not lead to the desired effect, you need to evaluate lights in your vertex shader (for per-vertex lighting) or fragment shader functions (for per-pixel lighting) to multiply the color intensity accordingly. Also note that URP, URP-2D and standard-pipeline shaders all use a different lighting evaluation setup, so be sure to choose your reference shader accordingly. -
No backface culling
(Spine-Skeleton.shader:23)
The only strict requirement for rendering Spine skeletons is to disabling backface culling, which is typical for 2D shaders.
Most 3D shaders will have backface culling enabled. With Spine meshes, this will cause some triangles to become invisible when parts are scaled negatively or if you flip your skeleton direction.
-
No fog
TheSpine/Skeleton
shader is not affected by fog.Enabling fog at your shader will require some additional vertex parameters and function calls added to your shader code. From
UnityCG.cginc
:hlsl
multi_compile_fog Will compile fog variants.
UNITY_FOG_COORDS(texcoordindex) Declares the fog data interpolator.
UNITY_TRANSFER_FOG(outputStruct,clipspacePos) Outputs fog data from the vertex shader.
UNITY_APPLY_FOG(fogData,col) Applies fog to color "col". Automatically applies black fog when in forward-additive pass.
Can also use U N I T Y_ A P P L Y_ F O G_ C O L O R to supply your own fog color.You can have a look at the
Spine/Sprite/Unlit
shader on how to apply fog in your shader:hlsl
#pragma multi_compile_fog
(SpritesUnlit.shader:70)
hlsl
UNITY_FOG_COORDS(1) // to declare it at the free attribute TEXCOORD1
(SpriteUnlit.cginc:L24)
hlsl
UNITY_TRANSFER_FOG(output,output.pos);
(SpriteUnlit.cginc:46)
-
Uses vertex colors to tint the texture via multiply
See Premultiply Alpha (PMA) blending above. -
Optionally uses straight-alpha instead of PMA textures
Since theSpine/Skeleton
shader's blend mode is constantly set to PMA blending, an input texture without premultiplied alpha colors needs to be converted to a PMA color after sampling. The following lines implement this feature:// bool Material parameter, enables the _STRAIGHT_ALPHA_INPUT shader keyword when enabled
[Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0
..
// compiles the shader in two variants so that shader keywords can switch between both variants
#pragma shader_feature _ _STRAIGHT_ALPHA_INPUT
..
// when enabled, multiply texture rgb values by the texture alpha value.
#if defined(_STRAIGHT_ALPHA_INPUT)
texColor.rgb *= texColor.a;
0 Response to "how to attach script to object created only in runtime unity"
Post a Comment