需要多套带有骨骼的模型文件,模型的骨骼要一致,需要换装的部位是分离状态,在基础模型上挂脚本ChangeCloth
代码:
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
public class ChangeCloth : MonoBehaviour {
//要更换装备的第二套模型
public GameObjec person_2;
//基础模型的SkinndeMeshRenderer组件
public SkinnedMeshRenderer MyskinMeshRender = null;
//换装模型的SkinndeMeshRenderer组件
public SkinnedMeshRenderer SrcSkinMeshRender = null;
void Update() {
//按C键换装
if(Input.GetKeyDown(KeyCode.C)) {
Change("Arm");
Change("Body");
}
}
void Change(string str) {
//对应子级的名称匹配要更换装备的部位
MyskinMeshRender = transform.Find(str).GetComponent<SkinnedMeshRenderer>();
SrcSkinMeshRender = person_2.transform.Find(str).GetComponent<SkinnedMeshRenderer>();
//基础模型的所有Transform信息
Transform[] bonesMy = gameObject.GetComponentsInChildren<Transform>();
//换装模型的所有Transform信息
Transform[] bonesSrc = SrcSkinMeshRender.bones;
//储存换装的信息
List<Transform> bones = new List<Transform>();
foreach (Transform boneM in bonesSrc) {
foreach (Transform boneS in bonesMy) {
if (boneM != null && boneS != null) {
if (boneM.name != boneS.name) {
continue;
}
bones.Add(boneS);
}
}
}
//换装赋值
MyskinMeshRender.bones = bones.ToArray();//骨骼信息赋值
MyskinMeshRender.sharedMesh = SrcSkinMeshRender.sharedMesh;//Mesh赋值
MyskinMeshRender.sharedMaterials = SrcSkinMeshRender.sharedMaterials;//材质球赋值
}