1.换装原理:
把人体分成各个部件, 比如头, 上半身, 下半身, 手, 脚等, 每个部件制作多个不同的Mesh, 但是这些部件共享同一套 人体骨骼 (挂件可以不用这样, 比如 帽子). 所以这种制作方式的换装就是替换不同部位的Mesh, 再搭配不同的材质更加灵活
所谓unity里的换装,通俗讲就是:改变mesh.
2.基本代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangeClothes : MonoBehaviour
{
//前提是需要有做好的骨骼,把此脚本挂载上
public List<GameObject> gameObjects = new List<GameObject>();//放置的头部,衣服等
// Start is called before the first frame update
void Start()
{
List<CombineInstance> combineInstances = new List<CombineInstance>();
List<Material> materials = new List<Material>();
for (int i = 0; i < gameObjects.Count; i++)
{
CombineInstance ins=new CombineInstance();
ins.mesh = gameObjects[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMesh;
combineInstances.Add(ins);
materials.Add(gameObjects[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMaterial);
}
Mesh mesh = new Mesh();
mesh.CombineMeshes(combineInstances.ToArray(),false,false);//合并mesh
GetComponent<SkinnedMeshRenderer>().sharedMesh = mesh;//应用mesh
GetComponent<SkinnedMeshRenderer>().materials = materials.ToArray();//材质保持一样
Transform[] allbones=GetComponentsInChildren<Transform>();
Dictionary<string,Transform> dic=new Dictionary<string,Transform>();
foreach (Transform t in allbones)
{
dic.Add(t.name, t);
}
List<Transform> mybones=new List<Transform>();
for (int i = 0;allbones.Length > i; i++)
{
Transform[] bodybones = gameObjects[i].GetComponentInChildren<SkinnedMeshRenderer>().bones;
for (int j = 0;bodybones.Length > j; j++)
{
if (dic.ContainsKey(bodybones[j].name))
{
mybones.Add(dic[bodybones[j].name]);
}
}
}
GetComponent<SkinnedMeshRenderer>().bones= mybones.ToArray();
}
上面就是基本换装代码,改变gameobjects集合里的东西,再通过改变mesh,material,最后把骨骼用上就能实现换装效果.
3.效果演示
水平有限,没有制作动图.