Thursday, February 13, 2014

Resources.Load


Resources.Load is an important (and dangerous) way of loading assets in runtime in Unity. The dangerous part is that once a resource is loaded, it will stay loaded until manually clearing it with UnloadAsset (Note: You can also use UnloadUnusedAssets to unload all assets that are currently not used - sort of like activating the garbage collector).

If you'll try loading a Sprite asset using Resources.Load<Sprite>, it will return null. The reason for that inconsistent behavior is the internal naming convention of unity. Unity creates a Sprite asset for each Texture2D which is marked as Sprite in the importer. The name of the sprite created is the same as the original Texture2D. When using Resources.Load, it will try loading the Texture2D and stop there, ignoring the Sprite. You can observe this behavior by trying to use LoadAll and for each file in the directory, print the name and the type - you will get 2 files of each name: one Texture2D and one Sprite.

The easy way to overcome this is to use Resources.LoadAll<Sprite> and put in the full path and not just the directory (the same path you would have used for Resources.Load). The documentation states:
If path refers to a file, only that asset will be returned. Only objects of type T will be returned.
This is correct. You will get an array of Sprites with a length of 1 which contains only the sprite you chose. This sounds like a workaround, and it in fact is. But there's no way around it unless the Unity team decide to either change the sprite naming convention of the engine or change Load<T> to ignore the first file it finds if it's of the wrong type.

Sprite image is property of Philipp Lenssen.