Inventory system in unity c#

In the inventory I want that we have a list of items and we can instantiate them with buttons or number keys (each key representing a right index in our list) and a way to drop stuff from our inventory and add stuff to it. Lets start. First things first. We will be using lists in this code so we need to add “using System.Collections.Generic;” to the start if the code.

using UnityEngine;
using System.Collections;
//Required if you will be using lists and we will.
using System.Collections.Generic;

public class Inventory : MonoBehaviour {

}

After that let’s think a bit what will we need. First off we need a class which we will store in to the list we will be making. Let’s go ahead and make a Weapon class that will hold all sub weapons we might do. First we want to make weapontypes. Enums work great with this and it’s a great way to check if some weapon is right type and stuff. 1st enum will be 1 second will be 2 and so on. Then we can add texture to specific weapons and use it later in inventory. And last we might want to add dmg float to this class as every weapon will be doing dmg.

using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

	public enum WeaponType
	{
		Sword,
		Gun
	};

	public WeaponType weaponType;
	public Texture weaponLogo = null;
	public float dmg = 0;
}

Now that we have a class for weapon we can jump back to the Inventory script. Let’s go ahead and add a list that will hold our weapons.

public List<Weapon> myWeaponList = null;

Then we need to be able to see which weapon we have currently selected(equipped) so lets make a variable for that.

public List<Weapon> myWeaponList = null;
public Weapon currentWeapon = null;

Alright now we have variables set so let’s go ahead and test them. As we want every weapon in our inventory to present box in our UI and to be able to change weapon by clicking one we need to make OnGUI function. We need to add rect which is 2d position on the screen with values “Position X, Position Y, Width, Height”.

public List<Weapon> myWeaponList = null;
public Weapon currentWeapon = null;
//We set all the values in a rect to 0 by default and we will set them in the inspector. After that let's test out how it works.
public Rect guiAreaRect = new Rect(0,0,0,0);

void OnGUI()
{
	//begin guilayout area
    GUILayout.BeginArea(guiAreaRect);
	//begin vertical group. This means that everything under this will go from up to down
    GUILayout.BeginVertical();
	//loop throught the list of out weapons
    foreach(Weapon weapon in myWeaponList)
    {
		//check if we find something
        if(weapon != null)
        {
			//Do a gui button for every weapon we found on our weapon list. And make them draw their weaponLogos.
            if(GUILayout.Button(weapon.weaponLogo,GUILayout.Width(50),GUILayout.Height(50)))
            {
				//if we clicked the button it will but that weapon to our selected(equipped) weapon
                currentWeapon = weapon;
            }
        }
    }
	//We need to close vertical gpr and gui area group.
    GUILayout.EndVertical();
    GUILayout.EndArea();
}
}

Then in editor side we click “GameObject” tab and “Create Empty” and attach our script to it. Then we set up our values in the inspector to the script. Now we need to make weapon to add to the Inventory, so let’s make GameObject again but this time let’s do a cube. Then we put weapon script to that cube. Now we drag that cube from Hierarchy to Assests folder and make it a prefab by doing so. Let’s name it to “Weapon1”. And then drag it to the Inventory.

MakingInventory
Now if we hit play it will show us one gui box presenting our weapon in our inventory. Now we add a texture (Just make one with paint or download from google) to Weapon1 and make another cube and make it “Weapon2”. Attach weapon script to that one too, make it a prefab and  drag it to our weapon list. Put different texture to it and then we click play again. We will see that there is texture in the box that is the texture from our Weapon1 and there will be second box with differend texture from weapon2. Now if we click that button we see that nothing will happen. Well there still happens something. If we press the button it will put that weapon in to our currentWeapon variable in our Inventory representing that that one weapon have been selected from the list.

InventoryTest2

We can add debug log aswell to print out current weapon


if(GUILayout.Button(weapon.weaponLogo,GUILayout.Width(50),GUILayout.Height(50)))
{
	//if we clicked the button it will but that weapon to our selected(equipped) weapon
	currentWeapon = weapon;
	Debug.Log(currentWeapon);
}

Now we have all these weapons in our inventory list, but they aren’t going to do anything if they just stay in the inventory, so we need a way to get them to the game and Instantiate them to our player’s hand for example. So we are going to go ahead and make empty gameobject again and put/attach that to anything anywhere in the screen. We will use this spot’s position to know where to spawn our weapon. Let’s make a new function let’s call it ChangeWeapon we need to pass it Weapon type variable which will be our new weapon to equip.

public void ChangeWeapon(Weapon newWeapon)
{

}

Now we need new variable that will represent our current weapon’s gameobject. And one that will have our weaponslots transform.

public Transform weaponPos = null;
public GameObject currentWeaponGO = null;

Then we can jump back to our function and actually do something. Firstly we need to make sure that there is no weapon already in our weaponslot. So let’s go ahead and make a check if there is a weapon and if there is destroy it. Now that we are sure that there is nothing in our weapon slot we can instantiate our currentweapon to our weaponslot. Then we set it to be a child of our weaponslot to make sure that it sticks along when we move our character. And depending which way our weapon is in prefab we need to turn it around to make sure it has right rotation.

public void ChangeWeapon(Weapon newWeapon)
{
	//if we have weapon destroy it
	if(currentWeaponGO != null)
		Destroy (currentWeaponGO);

	//instantiate new weapon prefab to game. it needs to be casted to be a gameobject
	currentWeaponGO = GameObject.Instantiate(newWeapon.gameObject,Vector3.zero,Quaternion.identity) as GameObject;
	//set weaponslot to be the parent of the weapon
	currentWeaponGO.transform.parent = weaponPos;
	//set weapon position to weaponslot position
	currentWeaponGO.transform.position = weaponPos.position;
	//turn weapon so it has right rotation ( not always needed )
	//currentWeaponGO.transform.localRotation = Quaternion.Euler(75f,75f,75f);
}

Now we call this function in OnGUI and when we have clicked the button.

if(GUILayout.Button(weapon.weaponLogo,GUILayout.Width(50),GUILayout.Height(50)))
{
	//if we clicked the button it will but that weapon to our selected(equipped) weapon
	currentWeapon = weapon;
	//we pass this function the value from our clicked button's weapon.
	ChangeWeapon(weapon);
	Debug.Log(currentWeapon);
}

InventoryTest3

Now let’s add another way to spawn or currentWeapon to weaponslots. In the start I said that we want to be able to spawn our currentWeapon with numbers. Number one representing first index in our list and so on. So let’s jump into it. Firstly we need a list about keys we will use. Unity holds all keyboard input keys in keycode enums. For example Keycode.Alpha1 is button 1 in keyboard. So let’s make a list about the keys we need. Let’s just add 5 first keys now in the start. We can add more later on if we need more for our inventory.

List<KeyCode> numberss = new List<KeyCode>{ KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3,
		KeyCode.Alpha4, KeyCode.Alpha5};

Now we need to make an update function to check out if we press those buttons.

void Update()
{

}

Then we make another function that we call from update.

public void ChangeWeaponWithNumbers()
{
}

So in this function we need to loop throught our keys and check if we press 1st key in our index it will spawn 1st index in our inventory.

public void ChangeWeaponWithNumbers()
{
	//loop throught our keycode list
	for(int i =0;i<numberss.Count;i++)
	{
		//check if whichever index keycode we have pressed
		if(Input.GetKeyDown(numberss[i]))
		{
			//set our currentWeapon to be same in our inventory as it is in our keycode list.
			currentWeapon = myWeaponList[i];
			// call weapon spawn function with that weapon.
			ChangeWeapon(myWeaponList[i]);
		}
	}
}

Now we call this function in our update function. Game goes throught Update function every frame. So for example if our fps is 60 it will go throught update fucntion 60 times in a second.

void Update()
{
	ChangeWeaponWithNumbers();
}

Okay now we notice that we get errors if we press key 3 and so on. Thats becouse there is no elements in our inventory at that point. To fix the error add empty elements to our weaponlist to have same amount as we have keycodes in our keycode list. And then we need to make one check aswell.

public void ChangeWeaponWithNumbers()
{
	//loop throught our keycode list
	for(int i =0;i<numberss.Count;i++)
	{
		//check if there is something before we instantiate it
		if(myWeaponList[i] != null)
		{
			//check if whichever index keycode we have pressed
			if(Input.GetKeyDown(numberss[i]))
			{
				//set our currentWeapon to be same in our inventory as it is in our keycode list.
				currentWeapon = myWeaponList[i];
				// call weapon spawn function with that weapon.
				ChangeWeapon(myWeaponList[i]);
			}
		}
	}
}

Let’s leave it here for now. Next time we will add a way to drop weapons from our inventory and add weapons to it. And I will propably go throught some basic networking in Unity and some other things in the future.

InventorytTutorial