Skip to content

Instantly share code, notes, and snippets.

@crazii
Last active August 1, 2019 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazii/e3926f21ed31d6d95414aa60f216f0a6 to your computer and use it in GitHub Desktop.
Save crazii/e3926f21ed31d6d95414aa60f216f0a6 to your computer and use it in GitHub Desktop.
Simple skeletal animation debug viewer for Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HierarchyViewer : MonoBehaviour {
public Material m_Material; //better use a material that disables ZWrite & ZTest.
class Joint
{
public Transform p;
public Transform c;
public GameObject hint;
}
List<Joint> joints = null;
// Use this for initialization
void Start () {
joints = new List<Joint>();
Stack<Transform> ts = new Stack<Transform>();
ts.Push(gameObject.transform);
while (ts.Count != 0)
{
Transform t = ts.Pop();
int n = t.childCount;
for (int i = 0; i < n; ++i)
{
Transform c = t.GetChild(i);
GameObject g = GameObject.CreatePrimitive(PrimitiveType.Capsule);
g.name = c.name + "_VIS";
g.GetComponent<Renderer>().sharedMaterial = m_Material;
Joint j = new Joint();
j.p = t;
j.c = c;
j.hint = new GameObject(c.name + "_VIS_PARENT");
g.transform.parent = j.hint.transform;
joints.Add(j);
ts.Push(c);
}
}
}
private void OnEnable()
{
if(joints != null)
{
for (int i = 0; i < joints.Count; ++i)
{
if (joints[i].hint != null)
joints[i].hint.GetComponentInChildren<Renderer>().enabled = true;
}
}
}
private void OnDisable()
{
if (joints != null)
{
for (int i = 0; i < joints.Count; ++i)
{
if (joints[i].hint != null)
joints[i].hint.GetComponentInChildren<Renderer>().enabled = false;
}
}
}
// Update is called once per frame
void Update () {
for (int i = 0; i < joints.Count; ++i)
{
Joint j = joints[i];
Transform t = j.hint.transform;
Renderer r = j.hint.GetComponentInChildren<Renderer>();
Vector3 posP = j.p.position;
Vector3 posC = j.c.position;
Vector3 mid = (posC + posP) * 0.5f;
Vector3 dir = (posC - posP);
float len = dir.magnitude;
if (len < 1e-5f || i == 0)
// j.hint.HideFlags = HideFlags.HideAndDontSave;
r.enabled = false;
//else
// j.hint.hideFlags = HideFlags.None;
//the transform is based on Unity's capsule geometry. (Centered pivot, Y scale doubles the len/height)
Transform cap = t.GetChild(0);
cap.localScale = new Vector3(0.1f, 0.5f, 0.1f) * len;
cap.localRotation = Matrix4x4.Rotate(j.c.rotation).inverse.rotation * Quaternion.LookRotation(dir.normalized) * Quaternion.FromToRotation(Vector3.forward, Vector3.up);
t.rotation = j.c.rotation;
t.position = mid;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment