Last active
April 14, 2020 11:30
-
-
Save gekidoslair/e8512f7a834c8bf46ce5d30c8ddc410e to your computer and use it in GitHub Desktop.
Bind clothing mesh to a parent character skin / rig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
namespace PixelWizards.CharacterCustomizer | |
{ | |
/// <summary> | |
/// attach this to the clothing GO you want to attach (the GO with the SkinnedMeshRenderer) | |
/// drag the main character body you want to attach it to (the GO with the SkinnedMeshRenderer) | |
/// the clothing rig must have been the same rig the character's body used. the body parts (transforms) must be named the same thing | |
/// </summary> | |
[ExecuteInEditMode] | |
public class CharacterMeshBind : MonoBehaviour | |
{ | |
public Transform characterRigRoot; | |
public SkinnedMeshRenderer baseCharacterMesh; //the character's main body | |
public SkinnedMeshRenderer clothingToAttach; //the clothing you want to attach | |
[ContextMenu("Bind Clothing to Character")] | |
private void BindClothingToCharacter() | |
{ | |
if (characterRigRoot != null) | |
{ | |
CopyArmature(); | |
} | |
} | |
private void CopyArmature() | |
{ | |
Debug.Log("CopyArmature()"); | |
Debug.Log("Finding bones in source body"); | |
Dictionary<string, Transform> bones = new Dictionary<string, Transform>(); //main body bones | |
var characterRig = characterRigRoot.GetComponentsInChildren<Transform>(); | |
foreach (Transform bone in characterRig) //make a dict for easy transform lookup | |
{ | |
Debug.Log("found bone: " + bone.name); | |
bones[bone.name] = bone; | |
} | |
List<Transform> replacementBones = new List<Transform>(); //this will hold | |
Debug.Log("map to bones in clothing mesh"); | |
foreach (Transform bone in clothingToAttach.bones) | |
{ | |
if (bones.ContainsKey(bone.name)) | |
{ | |
Debug.Log("Bone match: " + bone.name); | |
replacementBones.Add(bones[bone.name]); | |
} | |
else | |
{ | |
Debug.Log("bone " + bone.name + " not found?"); | |
} | |
} | |
clothingToAttach.bones = replacementBones.ToArray(); //convert the list to an array and assign | |
clothingToAttach.transform.SetParent(characterRigRoot, false); //move the clothing over to the body GO | |
clothingToAttach.rootBone = baseCharacterMesh.rootBone; //point it to the new root bone. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment