- Published on
Getting a Bone Transform from a Humanoid Animator in Unity Scripting
- Authors
- EvelynFull-time IndieDev.I'm Japanese, so please forgive me if my English is strange.
Thank you for visiting Evelyn GameDev Blog.
It's not uncommon for people to think, "I don't know what to do.
Isn't that what you think sometimes?
When you want to display an effect at a specific bone position of a character, it is useful to be able to easily transform the bone from a C Sharp script.
Table of Contents
Prerequisite
First, make sure that the Rig's AnimationType for the model you are using is set to Humanoid.
There are fixed types of humanoid rigs, such as Spine and Hip, etc.... And each has a corresponding bone Transform assigned to it.
Overview of the code
To get the joint of Transform from the Animator, use the method GetBoneTransform.
Unity Doc of Animator.GetBoneTransformYou can get all the bones at once with the following code.
If you want to get the transform of the head bone, you can do so by writing the following.
//Get Animator
Animator animator = GetComponent<Animator>();
//Get the Transform of the head (head), check in the log)
Transform head = animator.GetBoneTransform(HumanBodyBones.Head);
Debug.Log($"Hip : {head.name} : {head.position}");
GetBonesOfHumanoid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
[RequireComponent(typeof(Animator))]
public class GetBonesOfHumanoid : MonoBehaviour
{
private Animator _anim;
void Awake()
{
_anim = GetComponent<Animator>();
}
private void Start()
{
foreach (HumanBodyBones boneId in Enum.GetValues(typeof(HumanBodyBones)).Cast<HumanBodyBones>())
{
Debug.Log($"boneId: {boneId}, int: {(int)boneId}");
if ((int)boneId >= (int)HumanBodyBones.LastBone)
{
break;
}
Transform bone = _anim.GetBoneTransform(boneId);
if (bone)
{
Debug.Log(bone.name);
Debug.Log(bone.position);
// TODO: Implement as you see fit for your project.
}
}
}
}
After running this code, We can get the Transform information for each Bone in the console as shown below.
Wrap up
In this article, we got the bones of Humanoid from the script.
Using the GetBoneTransform method
I hope the contents of this article are useful to you.