Skip to content

Instantly share code, notes, and snippets.

@mafaca
Created March 27, 2019 20:25
Show Gist options
  • Save mafaca/3c2a73222eb0271c0047a4e0df8ee88c to your computer and use it in GitHub Desktop.
Save mafaca/3c2a73222eb0271c0047a4e0df8ee88c to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class SkinnedBoneSetter : MonoBehaviour
{
/// <summary>
/// Format:
/// - 3066451557
/// - 4026263382
/// - 1403723898
/// - 3027782206
/// </summary>
[Multiline]
public string m_boneNames = null;
public Transform m_root = null;
public SkinnedMeshRenderer m_skin = null;
private void Start()
{
List<uint> hashes = new List<uint>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m_boneNames.Length; i++)
{
char c = m_boneNames[i];
if (char.IsDigit(c))
{
for (int j = i; j < m_boneNames.Length && char.IsDigit(m_boneNames[j]); i++, j++)
{
sb.Append(m_boneNames[j]);
}
string numberString = sb.ToString();
uint number = uint.Parse(numberString);
hashes.Add(number);
sb.Length = 0;
}
}
Dictionary<uint, Transform> bones = GetBones(m_root);
List<Transform> skinBones = new List<Transform>();
foreach (uint hash in hashes)
{
Transform bone;
if (bones.TryGetValue(hash, out bone))
{
skinBones.Add(bone);
}
else
{
Debug.LogWarning("Can't get bone for " + hash);
skinBones.Add(null);
}
}
m_skin.bones = skinBones.ToArray();
}
private Dictionary<uint, Transform> GetBones(Transform root)
{
string rootName = root.gameObject.name;
uint rootHash = unchecked((uint)Animator.StringToHash(rootName));
Dictionary<uint, Transform> bones = new Dictionary<uint, Transform>();
bones.Add(rootHash, root);
CollectChilds(root, rootName, bones);
return bones;
}
private void CollectChilds(Transform node, string path, Dictionary<uint, Transform> hashes)
{
for (int i = 0; i < node.childCount; i++)
{
Transform child = node.GetChild(i);
string childPath = path + '/' + child.gameObject.name;
uint childHash = unchecked((uint)Animator.StringToHash(childPath));
hashes.Add(childHash, child);
CollectChilds(child, childPath, hashes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment