using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public class SkinnedMeshComponentWizard : ScriptableWizard { public SkinnedMeshRenderer baseMesh; public List components; [MenuItem("Tools/Mesh/Generate Skinned Mesh Component")] protected static void CreateWizard() { DisplayWizard("Skinned Mesh Component Generation", "Generate"); } protected void OnWizardCreate() { foreach (SkinnedMeshRenderer component in components) { Dictionary boneMapping = new Dictionary(); for (int i = 0; i < component.bones.Length; i++) { Transform compBone = component.bones[i]; for (int j = 0; j < baseMesh.bones.Length; j++) { Transform baseBone = baseMesh.bones[j]; if (compBone.name == baseBone.name) { boneMapping.Add(i, j); break; } } } //remap the bones BoneWeight[] weights = component.sharedMesh.boneWeights; for (int i = 0; i < weights.Length; i++) { BoneWeight weight = weights[i]; try{ weights[i].boneIndex0 = boneMapping[weight.boneIndex0];} catch{ weights[i].boneIndex0 = 0;} try{ weights[i].boneIndex1 = boneMapping[weight.boneIndex1];} catch{ weights[i].boneIndex1 = 0;} try{ weights[i].boneIndex2 = boneMapping[weight.boneIndex2];} catch{ weights[i].boneIndex2 = 0;} try{ weights[i].boneIndex3 = boneMapping[weight.boneIndex3];} catch{ weights[i].boneIndex3 = 0;} } Vector3[] vertices = component.sharedMesh.vertices; Vector3 scale = component.transform.lossyScale; for (int i = 0; i < vertices.Length; i++) { Vector3 vertex = vertices[i]; vertex.x *= scale.x; vertex.y *= scale.y; vertex.z *= scale.z; vertices[i] = vertex; } Mesh mesh = new Mesh { name = component.sharedMesh.name, vertices = vertices, uv = component.sharedMesh.uv, subMeshCount = component.sharedMesh.subMeshCount, //triangles = component.sharedMesh.triangles, bindposes = baseMesh.sharedMesh.bindposes, boneWeights = weights, normals = component.sharedMesh.normals, colors32 = component.sharedMesh.colors32, tangents = component.sharedMesh.tangents }; for(int i = 0; i < component.sharedMesh.subMeshCount; i++) { int[] tris = component.sharedMesh.GetTriangles(i); mesh.SetTriangles(tris, i); } AssetDatabase.CreateAsset(mesh, Path.Combine("Assets", "Export", $"{mesh.name}.asset")); } } protected void OnWizardUpdate() { helpString = "Creates a new mesh based off the bone structure of a base mesh and ensures everything is in the correct order in the new mesh."; isValid = (baseMesh != null) && (components != null && components.Count > 0); } }