发布时间:2017-08-28责任编辑:朱明 浏览:10736
最近研究spine在unity中实现换装,官方中有多种方案实现,差不多都试了一遍,但是有的方案不适合灵活的换装,在这里介绍一下我选择的方案。
导入spine运行库就不多说了(我用的是3.6版本的)。
先上代码:
using Spine;
using Spine.Unity;
using Spine.Unity.Modules.AttachmentTools;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class loadtest : MonoBehaviour
{
public SpriteRenderer visorSprite;
SkeletonAnimation skeletonAnimation;
Material sourceMaterial;
Skin customSkin;
Skeleton skeleton;
// Use this for initialization
void Start()
{
//读取路径下spine的SkeletonData文件
var yourSkeletonDataAsset = Resources.Load<SkeletonDataAsset>("spineboy/spineboy_SkeletonData");
SkeletonAnimation.AddToGameObject(this.gameObject, yourSkeletonDataAsset);
skeletonAnimation = this.gameObject.GetComponent<SkeletonAnimation>();
skeleton = skeletonAnimation.Skeleton;
//播放动画
skeletonAnimation.timeScale = 1.0f;
skeletonAnimation.loop = true;
skeletonAnimation.AnimationName = "run";
sourceMaterial = skeletonAnimation.SkeletonDataAsset.atlasAssets[0].materials[0];
//新建skin,并设置显示新的skin
customSkin = customSkin ?? new Skin("custom skin");
skeleton.SetSkin(customSkin);
StartCoroutine(changeGun());
}
IEnumerator changeGun()
{
//等到两秒
yield return new WaitForSeconds(2.0f);
//先写明要替换的服装绑定的slot的名字
string targetSlotName = "gun";
//查找到slot的数据
Slot targetSlot = skeleton.FindSlot(targetSlotName);
if (targetSlot == null)
{
Debug.Log("未找到Slot");
}
else
{
//slot的编号
int visorSlotIndex = targetSlot.Data.Index;
//获得初始的Attachment
Attachment templateAttachment = targetSlot.Attachment;
//要替换的图片,也可以读取路径加载
Sprite newSpr = visorSprite.sprite;
//复制初始的Attachment,并加载上新的图片
Attachment newAttachment = templateAttachment.GetRemappedClone(newSpr, sourceMaterial);
//把复制并替换好资源的Attachment添加到目标slot上
customSkin.SetAttachment(visorSlotIndex, templateAttachment.Name, newAttachment);
//设置显示新的服装
skeleton.SetAttachment(targetSlotName, templateAttachment.Name);
}
}
}
主要的步骤都有注释,不多解释了;
另外有个注意的地方就是要替换的图片的属性设置,一个meshType属性改成Full Rect,一个就是是否可读写属性。见下图:

最后看下效果图;
换装前:

换装后:

春秋工作室 供稿