Wednesday, October 26, 2011

Howto attach an object to a bone (Unity3D)

The basic principle of attaching any object to a bone of your animated model, is to make that objects transform a child of the bones transform. For example: parent the hand bones transform to the swords transform.

You could access the bones transform by script using
weapon.transform.parent = GameObject.Find(path to your bone).transform;

but this is quite unflexible. Instead take a look at the following script, which you could add as a seperate component to your animated model. (you can of course implement the code in your own classes too):

public var weapon:GameObject;
public var weaponBone:Transform;

function Start ()
{
 // instantiate the weapon prefab
 var weaponTransform:Transform = Instantiate(weapon, weaponBone.position, weaponBone.rotation) as Transform;

  // make the bone a parent of the weapon
 weaponTransform.parent = weaponBone;
}

Now you have to assign the bone of your animated model to the weaponBone variable. Find the bone in the Hierarchy panel and drag it to the variable slot in the Inspector. Attach the weapon by dragging your weapon Prefab to the weapon variable slot.

This way you can easily attach any object to any bone without hardcoding your armature structure.


Hint: You can only access a bone via the Hierarchy panel. If your model isn't already in your scene, you have to create a single instance, by dragging your animated model Prefab into the scene window. Find the bone in the Hierarchy and assign it to the variable slot. Click "Apply" in the Inspector panel to apply this change to your Prefab and remove the Instance from the scene.

1 comment:

  1. In Unity to spawn a prefab as a child of another object you just need to assign it to the desired parent object. Here's an example of how to do this, with a sample cube prefab:
    https://codeprozone.com/code/csharp/28533/unity-instantiate-prefab-as-child.html

    ReplyDelete