Contents - Quick Links
Creating the scripts to attach the object to the player
Next step in this unity attach object to player tutorial is to write the C# scripts to make the player wielding the weapon as he approaches it.
- Select the Player prefab and change the Tag field in the Inspector panel to the Player entry.
- In the Scripts folder create a new C# script named WieldWeapon. Open it in the code editor. Paste the following C# code :
- Add the WieldWeapon script as a component of the Sword object in the scene, and press the Play button in unity editor to see how the player will pickup the sword once near enough.
In this unity attach object to player tutorial we used a simple way to bind the sword model to the player right hand bone. First we identify the player and its hand bone where we want to attach the object with the Gameobject.Find method. Then we check every frame the distance between the object and the player and when they are close enough we attach the sword to the player’s hand by parenting the Sword transform component to the player’s hand bone transform component. The last steps in the code to attach the object to the player’s hand are resetting the rotation of the sword and then rotate it accordingly on how we want the character to wield the sword. You can see a video of the results of this unity attach object to player tutorial on Gameobject’s Youtube channel.
Download the full unity attach object to player tutorial project code
You can download the unity project file to import the completed project by clockin on the following link :