I am making a item system. I made the inventory. But i can’t seem to figure out how to make a way to add an item by an ID. For instance. A function that takes an ID. And when called. Returns the object with that ID.
Here’s my ScriptableObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu]
public class Items : ScriptableObject {
public Sprite itemSprite;
public string itemName;
public int itemId;
}
Have a InventoryManager in your scene that has a script such as this:
public class ItemManager : MonoBehaviour
{
private Dictionary<int, Items> m_ItemMap = new Dictionary<int, Items>();
public List<Items> Items;
private void Awake(){
foreach (var item in Items){
m_ItemMap.Add(item.itemID, item);
}
}
public Items Get(int id){
return m_ItemMap[id];
}
}
This will require you to assign the items to the Items list in the inspector. A slightly better way may be to use Resources.FindObjectsOfTypeAll to find all your Items objects in Awake and put those into the dictionary directly.