Item Registry System

I am trying to make an item registry system so I can access Item Prefabs and spawn them really easy but I’ve run into a couple roadblocks.

With this system, I am trying not to have to rely on Resources.Load() unless absolutely necessary. Thus I am currently trying to implement it with an empty object on screen that acts as a singleton that stores all Item Prefabs so I don’t have to do anything.

However, there are two roadblocks I have run into. Firstly, if I use a dictionary to store items so I can key them by their item IDs, I can’t just drag in prefixes really easily and will be forced to use Resources.Load(). Secondly, if I use an array to store items, keying them by ItemID gets A LOT harder.

Is there another method to do this without having to rely on Resources.Load()? Or is there a much simpler way other people are doing it and I am just overthinking things?

Rather than using a dictionary, you can use an array of structs to create a fake dictionary that you can modify in the inspector. I quickly wrote up some code that I think achieves what you are looking for:

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

public struct ItemInfo
	public string itemID;
	public GameObject itemPrefab;

public class TestDict : MonoBehaviour 
	[SerializeField] private ItemInfo[] items = new ItemInfo[0];

	// Loops through the array of items, looking for a matching ID 
	public GameObject GetItem(string id)
		foreach (ItemInfo item in items)
			// If matching ID found, return that item's prefab
			if (item.itemID == id)
				return item.itemPrefab;

		// No matching ID, returning null
		return null;

You do know you can make your own enumerable/dictionary? You just have to implement the corresponding interfaces. You can change the behaviour so that it takes a GameObject and sets the key automatically. You should define your own comparer methods though, since it will be hard comparing prefabs quickly with default comparers.

Edit : @DaUr3 i just want to add this small thing : as mentionned in the comments, using ints as keys is the most efficient way of looking up items by key. That said, Unity seems to return InstanceID when GetHash is called, and it’s an int. So you might want to use those as keys.