← Back to unity
How to Attach and Toggle Weapons in Unity
22 Sep 26 (1mo ago)
Attaching and toggling a weapon on a character is best done using a Bone Socket hierarchy and SetActive() state management.
1. Create a Hand Socket
- Open your Character Prefab.
- Locate the Hand Bone (e.g.,
hips$\rightarrow$spine$\rightarrow$arm$\rightarrow$hand). - Right-click the Hand Bone $\rightarrow$ Create Empty, and name it
WeaponSocket. - Drag your Weapon Prefab inside
WeaponSocket. - Adjust the weapon’s transform position and rotation to align naturally in the character's palm.
2. Toggle Weapon Visibility via Script
Avoid using Instantiate or Destroy at runtime, as this causes performance spikes. Instead, toggle the weapon's active state.
Attach this script to your Character GameObject:
using UnityEngine;
public class WeaponManager : MonoBehaviour
{
[SerializeField] private GameObject weaponObject;
[SerializeField] private KeyCode toggleKey = KeyCode.E;
private Animator animator;
private bool isArmed = false;
private void Awake()
{
animator = GetComponent<Animator>();
if (weaponObject) weaponObject.SetActive(isArmed);
}
private void Update()
{
if (Input.GetKeyDown(toggleKey)) ToggleWeapon();
}
public void ToggleWeapon()
{
isArmed = !isArmed;
if (weaponObject) weaponObject.SetActive(isArmed);
if (animator) animator.SetBool("isArmed", isArmed);
}
}
3. Sync Animator Parameters
To prevent the character from playing unarmed poses while holding a item:
- Open the Animator tab and add a Bool parameter named
isArmed. - Create transitions between Unarmed and Armed locomotion states using
isArmedas the condition. - Alternative: Use an Animation Layer with an Avatar Mask to isolate upper-body weapon poses while keeping lower-body locomotion consistent.