原理就是用新造的部件和角色的骨骼进行重新对接。
demo的使用方法:
PartIdx设置要换那个部件[0,4],一共5个部件
EquipIdx设置要更换部件的装备索引[0,1],具体看我的ChangeEquip的PartList。
点击Test执行换装
//换装源码
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MyAvatar : MonoBehaviour { [System.Serializable] public class PartInfo { public GameObject DefaultPart; public GameObject NewPart; } //目前部件列表 public List<PartInfo> AvatorParts; /// <summary> /// 换装 /// </summary> /// <param name="idx">部件索引id</param> /// <param name="res">装备资源</param> public void ChangePart(int idx, GameObject res) { if (idx < 0 || idx >= AvatorParts.Count) { Debug.Log("out of range"); return; } //获得这个部件信息 var info = AvatorParts[idx]; //先删除新装备的 if (null != info.NewPart) { GameObject.Destroy(info.NewPart); info.NewPart = null; } if (null == res) {//脱装备,还原成默认装备 info.DefaultPart.SetActive(true); } else {//穿新装备 info.DefaultPart.SetActive(false); //实例化那个部件 var go = GameObject.Instantiate(res) as GameObject; //获得蒙皮Renderer var newSkin = go.GetComponentInChildren<SkinnedMeshRenderer>(); //要挂接的是带蒙皮Renderer var newPart = newSkin.gameObject; //挂上 newPart.transform.parent = info.DefaultPart.transform.parent; //在主角骨骼身体里找到该部件所需要的骨骼(这里有一点需求就是美术在做部件时是要带着骨骼的) var bones = new Transform[newSkin.bones.Length]; for (int i = 0; i < newSkin.bones.Length; i++) { bones[i] = FindChild(gameObject.transform, newSkin.bones[i].name); } //重新赋值骨骼 newSkin.bones = bones; //给当前部件信息赋值 info.NewPart = newPart; //删除剩下没用的东西 GameObject.Destroy(go); } } public static Transform FindChild(Transform t, string searchName) { foreach (Transform c in t) { string partName = c.name; if (partName == searchName) { return c; } else { Transform r = FindChild(c, searchName); if (r != null) { return r; } } } return null; } }
最后附上Demo
链接: http://pan.baidu.com/s/1jHpw3Im 密码: w4r6