Ben Traje
← 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

  1. Open your Character Prefab.
  2. Locate the Hand Bone (e.g., hips $\rightarrow$ spine $\rightarrow$ arm $\rightarrow$ hand).
  3. Right-click the Hand Bone $\rightarrow$ Create Empty, and name it WeaponSocket.
  4. Drag your Weapon Prefab inside WeaponSocket.
  5. 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:

  1. Open the Animator tab and add a Bool parameter named isArmed.
  2. Create transitions between Unarmed and Armed locomotion states using isArmed as the condition.
  3. Alternative: Use an Animation Layer with an Avatar Mask to isolate upper-body weapon poses while keeping lower-body locomotion consistent.