I’ve noticed a weird behaviour with Resources.FindObjectsOfTypeAll. Im trying to create a dictionary of my ingame items (theyre all scriptable objects) so I can save them / manage them using their IDs.
And now Ill try to describe the error itself. Every time the game I use the following function to get a list of all my items:
public static void UpdateLibrary()
{
dictionary = new Dictionary<int, Item>();
//some failed attempts at making LoadAll() work
//Item[] foundItems = Resources.LoadAll("Items") as Item[];
//Item[] foundItems = (Item[])Resources.LoadAll("Items/", typeof(Item)) as Item[];
//Item[] foundItems = (Item[])Resources.LoadAll("Items");
Item[] foundItems = (Item[]) Resources.FindObjectsOfTypeAll(typeof(Item));
if (foundItems == null || foundItems.Length == 0) { print("dictionary found no items"); return; }
for (int i = 0; i < foundItems.Length; i++)
{
print(foundItems[i].name);
dictionary.Add(foundItems[i].GetInstanceID(), foundItems[i]);
}
print("Dictionary scanned, "+dictionary.Count);
}
It kind of works, but it only finds some of my items. At runtime Im giving 2 items to my player and it finds those, but it just doesnt care about any other items UNLESS I click on an item in my assets. After I do that, on my next scan it finds the item I clicked on (it still doesnt care about any other items unless I also clicked them).
Oh, that makes a lot of sense. Can I somehow load all of my items so it can find them? Resources.LoadAll() would probably fix all of my problems, but I cant get it to work.
What exactly doesn’t work when you use “Resources.LoadAll()”? The “InvalidCastException:Cannot cast from source type to destination type.”-error you mentioned on Unity Answers or some other error?
Resources.FindObjectsOfTypeAll has nothing to do with the resources folder. It won’t work for you. Its a function used to search the scene and find everything that is loaded. Its used in some special cases where you want to do things like mess with Unity’s internals. Basically its a very advanced function that most developers won’t ever need or touch.
Yes its exactly that. I worked around it by doing this:
Object[] foundObjects = (Object[])Resources.LoadAll("Scriptable Objects/Items", typeof (Item));
Item[] foundItems = new Item[foundObjects.Length];
for (int i = 0; i < foundObjects.Length; i++ )
{
foundItems[i] = Instantiate(foundObjects[i]) as Item;
foundItems[i].name = foundObjects[i].name;
}
Is it even possible to get it to work without instantiating? I probably wouldn’t have to use instantiate if my Items were Objects and not Scriptable Objects.