Search Unity

Proper Way to Replace Skinned Mesh

Discussion in 'Animation' started by arnedirlelwy, Oct 4, 2019.

  1. arnedirlelwy

    arnedirlelwy

    Joined:
    Oct 4, 2019
    Posts:
    3
    I have a skinned character with a default shirt and pants and I want to replace the shirt and pants with other models during runtime. I was wondering what the proper workflow is for this?

    Details:
    I am currently Instantiating a copy of the shirt from the character. Then replacing the sharedMesh on it with an instantiation of a prefab of the new shirt/pants.
    Code (CSharp):
    1. public GameObject ReplaceSkinnedMesh(GameObject objectWithSMR, Mesh replacementMesh) {
    2.         // Store important var information.
    3.         SkinnedMeshRenderer smr = objectWithSMR.GetComponent<SkinnedMeshRenderer>();
    4.         Transform[] bones = smr.bones;
    5.         Transform rootBone = smr.rootBone;
    6.         Transform parent = objectWithSMR.transform.parent;
    7.         string name = objectWithSMR.name;
    8.         Material mat = smr.material;
    9.  
    10.         // Create new instance so shared mesh doesns't alter every other instance.
    11.         GameObject newObjectWithSMR = (GameObject)Instantiate(objectWithSMR, Vector3.zero, Quaternion.identity);
    12.  
    13.         // Replace old object with new stffg.
    14.         newObjectWithSMR.name = name;
    15.         newObjectWithSMR.GetComponent<SkinnedMeshRenderer>().bones = bones;
    16.         newObjectWithSMR.GetComponent<SkinnedMeshRenderer>().sharedMesh = replacementMesh;
    17.         newObjectWithSMR.GetComponent<SkinnedMeshRenderer>().rootBone = rootBone;
    18.         newObjectWithSMR.GetComponent<SkinnedMeshRenderer>().material = mat;
    19.         newObjectWithSMR.transform.SetParent(parent);
    20.  
    21.          Destroy(objectWithSMR);
    22.         return newObjectWithSMR;
    23.     }