Unity Attach Weapon to Character

UnityTagUnity Attach Weapon to Character

In the following tutorial i will guide you through the process of attaching a weapon to a character using unity engine with a little bit of c# coding.

Ready to start , lets go , fire up unity and make sure you have a basic character with the desired weapon to attach make sure both of them are visible in the scene

In this tutorial we assume that your character is already rigged and has a valid bone structure , we need that to specify where the weapon is going to be attached , for more information regarding character bones and rigging .

Regardless if your not using a humanoid character you can just attach the weapon to any sub-mesh or even the original mesh itself,

WeaponAttachment

Once you get everything setup you need to create a small script to attach the weapon to the character , the script will have 3 states ,

  • Idle Position
  • Handheld Position
  • Shooting Position

You can add as many states as you wish but for this tutorial we are going to cover the three above , so lets get started

Create new script called WeaponAttachment and attach it to the player game object

CreateNewScript
To create new script just right click anywhere in the project window and then expand the create list and choose C# Script make sure to name the script “WeaponAttachment” , then all you have to do is to attach that script to the player game object ,

To do that select the player game object from the hierarchy window and from the inspector window on the right choose Add Component and use the search box to find the script WeaponAttachment

AttachScript

Once added to the player game object all you need to do is write a simple script to get everything setup , to edit the script find it in the project window and double click to open the script editor window.

EditiorWindow

You should have a similar window shown above , now your ready to start coding .

We are going to try and make this a general script , which allows the user to attach any type of weapon to the script and it should work as expected , to do that we will need a game object handler to assign the desired weapon through the editor or even using another script to do that add the following lines

 

using UnityEngine;
using System.Collections;

public class WeaponAttachment : MonoBehaviour {

	//Weapon Gameojbect handler used to assign weapon
	public GameObject MainWeaponAttachment ;
        //private handle to store the weapon object for later use
        private GameObject WeaponSlot1;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

Next we are going to check if there is a weapon attached and then set the weapon into the idle state which will instantiate the weapon and set its position and rotation.

 

void Start ()
	{
		//Check if weapon Exists and set its inital location 
		if (MainWeaponAttachment != null) {
			//Create an instance of the weapon and set the state to idle
		        WeaponSlot1 = Instantiate (MainWeaponAttachment, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
			//Attach the weapon to the desired bone or submesh make sure its a child to the player object
			WeaponSlot1.transform.parent = GameObject.Find ("bodyrahall").transform;
			//Set the desired idle position for the weapon
			WeaponSlot1.transform.localPosition = new Vector3(-0.0005f,0.0011f,0);
			//set the desired idle rotation for the weapon
			WeaponSlot1.transform.localEulerAngles  = new Vector3(6.97f,42.36f,90f); 
		}

	}

 

Before you run the game make sure to attach a weapon to the WeaponAttachment script

AttachWeaponToCharacter

to do that select the play game object from the hierarchy window this will allow you to specify a value form Main Weapon Attachment variable , click the small black circle to select a weapon then use the search box in the Select Game Object window to find the desired weapon mesh , that’s it now your weapon should show up in the game and automatically set to idle state .

WeaponAttachedView

Great now we have a weapon attachment system that works , next we are going to build the handled state , and the shooting state , don’t worry it going to be a simple task

 

Time to update the code by adding some bits to manage character state , first make sure that you have configured an animator since we are going to use this to find which state we are in and update the weapon position you may follow this tutorial to learn more about animator.

Add new function called UpdateWeaponState and call it every frame using the update function

// Update is called once per frame
	void Update ()
	{
		//Call update weapon state on every frame 
		UpdateWeaponState ();
	}

	//This function updates the weapon state and updates its position and rotation
	void UpdateWeaponState(){

	}
}

Now we need to get the animator controller store it in a variable and get the current state of the player once we have the state we can change the weapon position and rotate accordingly , take look at the updated code

using UnityEngine;
using System.Collections;

public class WeaponAttachment : MonoBehaviour
{

	//Weapon Gameojbect handler used to assign weapon
	public GameObject MainWeaponAttachment ;
	private GameObject WeaponSlot1;
	//Animator refrence
	Animator anim;	

	// Use this for initialization
	void Start ()
	{
		//Set the animator component for later use 
		anim = GetComponent<Animator>();

		//Check if weapon Exists and set its inital location 
		if (MainWeaponAttachment != null) {
			//Create an instanec of the weapon and set the state to idle
			WeaponSlot1 = Instantiate (MainWeaponAttachment, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
			//Attach the weapon to the desired bone or submesh make sure its a child to the player object
			WeaponSlot1.transform.parent = GameObject.Find ("bodyrahall").transform;
			//Set the desired idle position for the weapon
			WeaponSlot1.transform.localPosition = new Vector3(-0.0005f,0.0011f,0);
			//set the desired idle rotation for the weapon
			WeaponSlot1.transform.localEulerAngles  = new Vector3(6.97f,42.36f,90f); 
		}

	}
	
	// Update is called once per frame
	void Update ()
	{
		//Call update weapon state on every frame 
		UpdateWeaponState ();
	}

	//This function updates the weapon state and updates its position and rotation
	void UpdateWeaponState(){

		//Execute the following code if the current state is idle
		if (anim.GetCurrentAnimatorStateInfo (0).IsName ("Idle")) {
			//Update weapon parent and position
			WeaponSlot1.transform.parent = GameObject.Find ("body rahall").transform;
			//Set the desired idle position for the weapon
			WeaponSlot1.transform.localPosition = new Vector3(-0.0005f,0.0011f,0);
			//set the desired idle rotation for the weapon
			WeaponSlot1.transform.localEulerAngles  = new Vector3(6.97f,42.36f,90f); 
		}

		//Execute the following code if the current state is Running
		if (anim.GetCurrentAnimatorStateInfo (0).IsName ("Running")) {
			//Update Weapon parent and position
			WeaponSlot1.transform.parent = GameObject.Find ("Base HumanLPalmGizmo").transform;
			//Set the desired idle position for the weapon
			WeaponSlot1.transform.localPosition = new Vector3(-0.03f,-0.07f,-0.13f);
			//set the desired idle rotation for the weapon
			WeaponSlot1.transform.localEulerAngles  = new Vector3(6.97f,4f,211f); 
		}

	}
}

You can see that we are using if statement to find the current state and we are checking between “Running” and “Idle” state , once final thing to do is to add the shooting state and we should be done for this tutorial .

 

//Execute the following code if shooting trigger is on
		if(anim.GetBool("Is_Shooting"))
		{
			//Update Weapon parent and position
			WeaponSlot1.transform.parent = GameObject.Find ("Base HumanLPalmGizmo").transform;
			//Set the desired idle position for the weapon
			WeaponSlot1.transform.localPosition = new Vector3(-0.03f,-0.07f,-0.13f);
			//set the desired idle rotation for the weapon
			WeaponSlot1.transform.localEulerAngles  = new Vector3(6.97f,4f,211f); 
		}

Finally we check if the shooting trigger is on and set the weapon position and rotation ,

 

Now you have a fully working weapon attachment system , there is still alot to be done in order to fix and improve some of the scripts keep in mind that the purpose of this tutorial is to get you started .

 

Hope you enjoyed this as much as i did , feel free to post comments i will gladly answer your questions .