The solution is not too complicated but kinda hard to figure out. Anyway, here is the soltution:
[Shared skeleton and animation state][1]
Also check this question thread from myself which I found the answer to:
[Weightless bones don’t get added to SkinnedMeshRenderer bone array?!?][2]
Finally, here is my modified script based on the code from the first link.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class test : MonoBehaviour {
public GameObject target;
public Transform rootBone;
//bones List gets all bones from the SkinnedMeshRenderer at Start()
public List<Transform> bones = new List<Transform>();
//boneArray Transform gets filled in the assign function. It has to have the same bones in it as the bones List, or there will be an error.
//If the main body mesh is missing any bones, try giving them weights or keyframes and export again.
public Transform[] boneArray;
void Update() {
if(Input.GetKey(KeyCode.Space)) {
if(target != null) {
AssignToActor();
}
}
}
void AssignToActor() {
//parent object to actor just in case, and move it there (although the bone movement technically takes care of it)
transform.parent = target.transform;
transform.localPosition = Vector3.zero;
SkinnedMeshRenderer targetRenderer = target.GetComponent<SkinnedMeshRenderer>();
Dictionary<string, Transform> boneMap = new Dictionary<string, Transform>();
foreach(Transform bone in targetRenderer.bones) {
boneMap[bone.name] = bone;
}
SkinnedMeshRenderer thisRenderer = GetComponent<SkinnedMeshRenderer>();
boneArray = thisRenderer.bones;
for(int i = 0; i < boneArray.Length; i++) {
string boneName = boneArray*.name;*
_ if(boneMap.TryGetValue(boneName, out boneArray*) == false) {_
_ Debug.LogError("failed to get bone: " + boneName);_
_ Debug.LogError(i);*_