Resources.LoadAll what's the difference between <GameObject>, typeof(GameObject), and as GameObject

Just curious, I’m somewhat new to this. What do these do different?:

Resources.LoadAll(“path”);
Resources.LoadAll(“path”, typeof(GameObject));
Resources.LoadAll(“path”) as GameObject;

They’re all basically the same, it’s related to what’s called casting and type conversion to ensure that the compiler knows what type of object you’re working with. The first one uses what’s called a generic function which allows you to explicitly define the type. The second one is a variant of the the first except you’re passing the type into the function itself. The third returns a generic Unity Object type which you convert using the as operator into a GameObject (or null if the cast is invalid).

1 Like

I’d add that for most Unity functions like these, if you’re not sure which to use, the generic version SomeFunction() is usually the “best” one to use in almost all cases.

2 Likes

The last one will actually always return null! The result of Resources.LoadAll(string) is an Object[ ], so when you do a safe cast (as) from Object[ ] to GameObject - ie. from an array type a non-array type - you’ll get null.

Also note that you can’t cast an Object[ ] to a GameObject[ ], so the last one is never relevant for arrays (which is what you get from LoadAll). For loading a single object, like what you get from Load, it’s fine

3 Likes

Thanks for the info, guys, it’s really helpful :slight_smile: