- Home /
Hello, could I get some help with my inv system?
I am very new to programming and I have dug a deep hole, and my head is currently under the ground. I have a script that can add an item to my hotbar inventory, even adds an icon to the button and I have assigned to OnClick event UseItem() function.
So I have created an itemDatabase by using a list and getitembyid(int itemID), and then i use items.find etc.
How would I go about to look through my hotbar buttons, and say search with the id, get the item from the database and then use it?
Here is my code for now,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
public List<GameObject> hotBarSlots = new List<GameObject>();
public Text showCurrentItemInfo;
public ItemDatabase itemDatabase;
public bool[] isSlotFull;
// Start is called before the first frame update
void Start()
{
AddItemToHotBar(new Item(0, 25.0f, "fps_healthheart_sprite"));
}
public void AddItemToHotBar(Item item)
{
for (int i = 0; i < hotBarSlots.Count; i++)
{
if(isSlotFull[i] == false)
{
isSlotFull[i] = true;
hotBarSlots[i].GetComponent<Image>().sprite = item.itemIcon;
showCurrentItemInfo.text = "ID: " + item.id + "Add Health: " + item.healthAmount;
print("Item Added! { ID: " + item.id + " }");
break;
}
}
}
public void UseItem()
{
for (int i = 0; i < hotBarSlots.Count; i++)
{
//Should I use a for loop here, to loop through all buttons and somehow get the itemID?
}
}
}
Answer by CodesCove · Nov 21, 2021 at 06:51 PM
So you want to check if certain item with certain itemID is in the hotbarsSlots? Well only thing that is related between the hotBar and actual Items is the itemIcon (Sprite).. the setup is nor very good but anyway this is how you find if the item is in the hotBarSolts by Item id (if that was the question??)
public bool IsItemInTheSlots(int id) => hotBarSlots.Exists(x => x.GetComponent<Image>().sprite.Equals(items.Find(x => x.itemID == id)?.itemIcon));
if the question was just about how to get the Item via specific slot then
public Item GetItemFromSlot(GameObject slot) => items.Find(x => x.itemIcon == slot.GetComponent<Image>().sprite);
This is also a great opportunity to find out about lambda expressions:)
I suggest however you get familiarized with Scriptable objects and utilize them in the Inventory system. There are also good tutorials for this.