How do I parent an object to a bone?

(I realize this question comes up frequently, however, the many answers didn’t seem to address my specific issue.)

I have a gun. I want to parent it to the hand of a character. Here is my simple code for doing so.

var weapon: GameObject;
weapon = Instantiate (gun, worm.leftWrist.position, worm.leftWrist.rotation);
weapon.transform.parent = worm.leftWrist;
Debug.Log (worm.leftWrist.rotation+" "+worm.leftWrist.localRotation);

The first two lines, by themselves, work fine. The gun lands in exactly the right place. However, the gun isn’t parented to the bone.

The third line parents the gun to the bone. This resets the gun’s rotation to a default rotation. In an attempt to figure out why the gun’s rotation changes on parenting, I wrote the fourth line, the Debug.Log. The result I get from Debug.Log is that both rotations are Vector4 (0.0, 0.0, 0.0, 1.0). However, when I actually go to the bone at the point of parenting, the rotation of the bone in the Inspector is X = 270, Y = 90, Z = 0. I don’t know Quaternions very well, but I’m pretty sure the Quaternion for that is not 0, 0, 0, 1.

So, how do I get the actual rotation value of a bone so that I can rotate the weapon properly after parenting the transform?

The localRotation will be Quaternion.identity because the object has the same rotation as the parent (you set it that way). .rotation will be the rotation of the parent. In other words as the gun has the same rotation as the parent then its localRotation will be Quaternion.identity.

If you want it to have some other rotation, parent it first and then set the rotation or set the rotation to be some other value in the Instantiate.

You have to write

weapon.transform.parent = worm.leftWrist.transform;

instead of just the Object.