I’m developing a shooter with both first- and third-person perspectives. I’m currently using the Hero model from the Locomotion System. That model comes with a gun that the man holds in his right hand. I want to be able to swap that gun for another weapon. I should be able to detach the gun mesh from his hand and attach another gun mesh, right? The gun needs to be attached to the model’s skeleton so it moves with the skeleton’s animations.
I thought that would be easy to do, but I can’t figure out how to do it. I’m a programmer, not a modeler, and meshes, bones, and animations are a bit of a mystery to me. Attaching and detaching meshes must be well understood. It occurs in a lot of games, especially RPGs, where all sorts of armor and weapons are swapped on and off the player’s character.
If this has been covered somewhere already, just point me in the right direction. I’ve spent hours looking for answers, but I’ve come up empty. I’ve googled 'til I can google no more! Any help will be greatly appreciated.
I don’t have a huge amount of experience with this area, but it seems anything with bones has the bone hierarchy in the unity editor. Design time, you can just drag and drop the attachable mesh onto the proper bone.
Run-time you’d need to find the proper bone and set the transform.parent via script (assuming you have instantiated something in the ‘weapon’ variable:
GameObject hand = GameObject.Find("character284/root/spineA/spineB/right_shoulder/right_forearm/right_hand");
// Your positioning adjustments go here
weapon.transform.position = hand.transform.position;
weapon.transform.rotation = hand.transform.rotation;
weapon.transform.parent = hand.transform;
I was having weird issues adjusting the position and rotation after the fact, but it should just follow the hand once the parent is set so adjusting it prior to attachment works just as well.
EDIT: Please note the model I used was not the same model you’re using, so replace the hierarchy in the code above with your own bone hierarchy.
EDIT 2: The problem with updating afterwards was because I was changing the wrong variables. If you want to adjust after the object is attached, you use local positioning (with the origin being the attachment point):