Inventory system 2D

Hello, I’m trying to make an inventory system for 2D top down game. I would like to pick up objects with a key and store it into my inventory. I should be able to see what items I have in my inventory and be able to drop them back in the scene with a key. I’m stack and have no idea what to do :face_with_spiral_eyes:. Any help would be grateful.
This is my code for the inventory:

public class Inventory : MonoBehaviour {

    public GameObject[] inventory = new GameObject[10];

    public void addItem (GameObject item)
    {
        bool itemAdded = false;
        //find the first open slot in the inventory
        for (int i = 0; i < inventory.Length; i++)
        {
            if(inventory [i] == null)
            {
                inventory[i] = item;
                Debug.Log(item.name  + " " + "was added");
                itemAdded = true;
                break;
            }
        }
        //inventory full
        if (!itemAdded)
        {
            Debug.Log("Inventory full!");
        }
    }

    public GameObject FindItemByType(string itemType)
    {
        for (int i = 0; i< inventory.Length; i++)
        {
            if(inventory[i] != null)
            {
                if(inventory[i].GetComponent<IntercationObject> ().itemType == itemType)
                {
                    //we found the type of item we wanted
                    return inventory[i];
                }
            }
        }
        //item not found
        return null;
    }

    public void removeItem (GameObject item)
    {
        for(int i = 0; i<inventory.Length; i++)
        {
            if(inventory[i] == item)
                //remove founded item
            {
                inventory[i] = null;
                Debug.Log(item.name + "was removed from the inventory");
                break;

            }
        }
    }
}

This is my code for the interaction with the object:

public class IntercationObject : MonoBehaviour {

    public bool inventory; // if true this item can be stored
    public string itemType; //this will tell what type of object it is

    public void DoInteraction()

    {
        //Picked and put into inventory
        gameObject.SetActive(false);
    }
}

This is my code for the interaction with the player:

public class PlayerInteraction : MonoBehaviour
{

    public GameObject currentInterObj = null;
    public IntercationObject currentInterObjScript = null;
    public Inventory inventory;

     void Update()
    {
        if (Input.GetButtonDown("Interact") && currentInterObj)
        {
            if (currentInterObjScript.inventory)
            {
                inventory.addItem(currentInterObj);
            }
            // Do something with the object
            currentInterObj.SendMessage("DoInteraction");
        }

        //Use item from inventory
        if (Input.GetButtonDown("Use item"))
        {
            //Check the inventory for an item
            GameObject Kost = inventory.FindItemByType("Bone");
            Debug.Log("nešto");
          
        }

    }


    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("interObject"))
        {
            Debug.Log(other.name);
            currentInterObj = other.gameObject;
            currentInterObjScript = currentInterObj.GetComponent<IntercationObject>();
        }
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("interObject"))
        {
            if (other.gameObject == currentInterObj)
            {
                currentInterObj = null;
            }

        }
    }
}

And this is my code for the GUI inventory:

public class GUIInventory : MonoBehaviour {
    private bool inventoryWindowToggle = false;
    private Rect inventoryWindowRect = new Rect(300, 100, 400, 400);
   

    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
        if(Input.GetButtonDown("ShowHideInventory"))
        {
            inventoryWindowToggle = !inventoryWindowToggle;
        }
       
    }

     void OnGUI()
    {
        inventoryWindowToggle = GUI.Toggle(new Rect(0, 0, 0, 0), inventoryWindowToggle, "inventory");
        if (inventoryWindowToggle)
        {
            inventoryWindowRect = GUI.Window(0, inventoryWindowRect, inventoryWindowMethod, "inventory");
        }
    }

    void inventoryWindowMethod(int WindowId)
    {
        GUILayout.BeginHorizontal();
        GUILayout.Button("Item 1", GUILayout.Height(50));
        GUILayout.Button("Item 2", GUILayout.Height(50));
        GUILayout.Button("Item 3", GUILayout.Height(50));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Button("Item 4", GUILayout.Height(50));
        GUILayout.Button("Item 5", GUILayout.Height(50));
        GUILayout.Button("Item 6", GUILayout.Height(50));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Button("Item 7", GUILayout.Height(50));
        GUILayout.Button("Item 8", GUILayout.Height(50));
        GUILayout.Button("Item 9", GUILayout.Height(50));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Button("Item 10", GUILayout.Height(50));
        GUILayout.EndHorizontal();

    }

}

I think that you should consider using a UI panel maybe with a GridLayout (and 10 ‘subpanels’) ; you can set the grid size properly so you get the 10 items you want , like 3x3 + 1 or however you’d like. I say this part because OnGUI is older code, and not recommended (except for maybe quick debugging and editor scripts*).

With that setup, you can use very similar code to add objects (to what you already have).

You didn’t specify how much of your code is already working or not…

As for dropping with a key, if you only ever want to have 10 items, then you can look through the items, as you in the remove method, and if it’s not null when you press a key (maybe you pressed # 5), you can Instantiate the object and place it next to you. If you ever have more than 10 objects, you start to run into an issue with “which key am I going to press?!?” :slight_smile: Then, you either have to select/highlight an object, then a key drops it or you lean towards right-click to drop or something else…

Hopefully that’s a good start. Please point out specific issues or parts that aren’t working or aren’t working as well as you’d like, etc… if you have more questions :slight_smile: I just took some guesses there, somewhat.

1 Like

Tnx for the replay. the code for the pick up is working, I can pick up the object and it shows up in my inventory. As you can see it in the picture. But I don’t know how to make that the object appears in UI inventory. The code to remove the object is not working and I also don’t know how to delete the item so that is shows up on the scene?

3084540--232348--inventory.jpg .

Well, did you try any of the things that I suggested for the UI/dropping items?

Yes, I made UI panel with a GridLayout for my inventory but I still have no idea how to make the items show up there when I pick them up :rage:

Well you’ll need sprites to fill in the slots, I’d think. You have to organize it so each game object that can go in your inventory has the equivalent of an “icon”. Then, when you pick it up, assign the icon to the appropriate spot. For instance, in your grid layout, you could add the number of images/panels to fill out your entire inventory and assign to those.

Do you have an example of code or something because I’m very new to game development and don’t really understand.

I can appreciate that you’re new. I’m hesitant on where to begin if I write code that you will not understand well.
I can give you some ideas…
Have a script on the game object that has a reference to the sprite icon that you would use in the inventory. That way, when you add the item to your inventory, you can lookup that script and find the corresponding icon to use for the inventory that players will see on the screen.
Basically you’re asking about a combination of a few simple practices (coding + unity) that used together to accomplish your task.
You would be much better off learning the parts of what I’m talking about piece by piece, instead of trying to get just the solution. You’ll reuse that knowledge a lot while making your game, so it won’t be wasted.

Please try to think about any (or each) of the suggestions we’ve discussed, and try to code the parts that you know, and look up the remaining parts to fill in the blanks.
If you do that, and you try to tie them together, and you still have any issue(s), then please feel free to post updated code about what’s working/not working at that time.

To get started, just try the script on the game object. Maybe called “InvInfo”
When you add an object (pick it up), try something like this:

void PickupItem(GameObject item) {
   InvInfo info = item.GetComponent<InvInfo>();
   Sprite sprite = info.spriteIcon;
   // Or you could just do : Sprite sprite = info.GetComponent<InvInfo>().spriteIcon;
   // rest of your code.. including applying the sprite in the UI/inventory.
   }

I’m not sure if I understood you but I made this two Scripts for my items:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemDataBase : MonoBehaviour {

    public List<Item> items = new List<Item>();

    private void Start()
    {
        ItemDataBaseSetup();
    }

    private void ItemDataBaseSetup()
    {
        items.Add(new Item(0, "Bone", "femur"));
    }

    public Item GetItemByID(int id)
    {
        foreach (Item itm in items)
        {
            if(itm.itemId == id)
            {
                return itm;
            }
        }
        Debug.LogError("Item can't be found!");
        return null;  
    }
}

And the other one:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Item  {

    public int itemId;
    public string itemName;
    public Sprite itemSprite;
    public string spriteName;

    public Item(int id, string name, string spName)
    {
        itemId = id;
        itemName = name;
        itemSprite = Resources.Load<Sprite>("ItemIcons" + spriteName);
        spriteName = spName;
       
    }
}

I think I should make a function like FindItemByID but not sure how to implement at or maybe repair my Add function but I’m not sure how to exactly do that.
Btw I really apreciate your help :slight_smile:

I think we should focus on the icon part first, okay? You didn’t write a script as I tried to explain in my last post.
One that goes on the game object that can reference the sprite. I understand that you may want a list and/or database, etc… there’s a long list of things one might do to create an inventory system.
But you were originally asking about icons and about dropping an item back into the world… So, it’s easier to work on that and not get carried away in every other detail.

Since my suggestions haven’t changed from my last post, I can only wait to see if you try the script to see what i’m talking about before continuing.