I need a dictionary for my items so I can reference them using their IDs. My items are scriptable objects. Theyre all in my “Resources/Items” folder.
Im trying to get them using Resources.LoadAll but it doesnt work, im getting a casting error:
InvalidCastException: Cannot cast from source type to destination type.
This is how my Resources.LoadAll looks:
Item[] foundItems = (Item[])Resources.LoadAll("Items/", typeof(Item)) as Item[];
As you can see I’ve been trying to fix it by putting Item everywhere but it doesnt help.
Item foundItems = (Item) Resources.FindObjectsOfTypeAll(typeof(Item));
That worked for me.
Have you tried this?
Item[] foundItems = (Item[])Resources.LoadAll("Items");
That most closely matches the example in the documentation.
Here’s a potential more modern answer to this problem:
You may be better off caching them into an array you create in the editor on a Component script. This probably wouldn’t be as convenient when working with a very large amount of items that change frequently.
So if manually creating an array isn’t copacetic for your use case, you could take a look at Addressables. https://docs.unity3d.com/Packages/com.unity.addressables@1.20/manual/index.html