Photo by Sincerely Media / Unsplash
Unity has preserved some special names for folders like: Assets, Editor, Streaming Assets and Resources. Today we are going to talk about the last one.
Unity allows developers to store Assets within one or more folders named Resources. Those assets can be loaded or unloaded at runtime using the Resources API.
For load assets purpose you can use Resources.Load method. It have 2 parameters:
The path is relative to any Resources folder inside the Assets folder of your project. So when you have structure Assets/RobotsAssets/Resources/head.jpg for example, your path should look like that: Resources.Load(“head”).
Important! — Do not include the file extension names (.txt, .jpg, .fbx) in the path parameter.
TextAsset textAsset = (TextAsset)Resources.Load("txtFilePath");
string txtFile = textAsset.text;
Texture2D textureAsset = (Texture2D)Resources.Load("textureFilePath");
Sprite spriteAsset = (Sprite)Resources.Load("spriteFilePath");
Sprite\[\] spriteAssets = Resources.LoadAll<Sprite>("spritesFilePath") as Sprite\[\];
AudioClip audioAsset = (AudioClip)Resources.Load("audioFilePath");
GameObject prefabAsset = (GameObject)Resources.Load("prefabFilePath");
Mesh modelAsset = (Mesh)Resources.Load("meshFilePath");
VideoClip videoAsset = (VideoClip)Resources.Load("videoFilePath");
You can load files from Resources folder asynchronously using this Coroutine method:
IEnumerator AsyncLoadResources()
{
ResourceRequest resourcesRequest= Resources.LoadAsync("anyPrefab", typeof(GameObject));while (!resourcesRequest.isDone)
{
Debug.Log("Loading progress: " + resourcesRequest.progress);
yield return null;
}
GameObject prefab = resourcesRequest.asset as GameObject;
}
Obviously to run this method you have to use this command:
StartCoroutine(AsyncLoadResources());
Don’t use it
There are some reasons that you shouldn’t use Resources:
In that case, why does Unity provide us Resources folder? There are some specific use cases where this system can be helpful:
Pro tip: Use
_Resources.UnloadUnusedAssets()_
to release memory and unload assets that are not used.
Unity’s Resources system is very helpful tool. However you must remember that you should use it only when it really necessary. Overusing of this system may cause increase of startup time and longer duration of building time.
I hope it’s useful for you. If you have any comments or questions, please write them here!
To help us create more free stuff, consider leaving a donation through Patreon where you can vote for the next asset pack and get access to future packs & articles earlier. Sharing knowledge is our passion. Unfortunately, keeping a team of professionals costs a lot that’s why we are constantly taking on new opportunities.
We’ll be publishing any news on the following outlets:
Thanks for reading!