Load and unload assets with the Resources system
Add assets to the Resources folder and use the Resources API to load and unload them.
Read time 2 minutesLast updated a month ago
To load assets with the Resources system:
- Create a new folder called in your project, and add assets to it. Unity then makes these assets available even if they're not directly referenced in a scene. Note: You can have multiple
Resourcesfolders located in different subfolders within yourResourcesfolder, and packages can also containAssetsfolders.Resources - Whenever you want to load an asset from one of these folders, call in your code. Only assets in the
Resources.Loadfolder can be accessed in this way.Resources
For example, you can apply the following script to load and apply a texture to it:
using UnityEngine;public class LoadTexture : MonoBehaviour{ // Reference a material to apply the texture to public Renderer targetRenderer; void Start() { // Load a texture from the Textures folder inside the Resources folder Texture2D loadedTexture = Resources.Load<Texture2D>("Textures/MyTexture"); if (loadedTexture != null) { // Apply the loaded texture to the material of the target renderer targetRenderer.material.mainTexture = loadedTexture; Debug.Log("Texture successfully loaded and applied."); } else { Debug.LogError("Failed to load texture from Resources."); } }}
Unity stores all assets in the folders and their dependencies in a file in the build output called . If a scene in the build references an asset, Unity serializes that asset into a file instead.
Resourcesresources.assetssharedAssets*.assetsAdditional assets might end up in the file if they're dependencies. For example, a material in the folder might reference a texture outside of the folder. In that case the texture is also included in the file, but isn't available to load directly.
resources.assetsResourcesResourcesresources.assetsUnload assets
If you want to destroy objects that loaded before loading another scene, call on them. To recover memory used by unreferenced objects, use .
Resources.LoadObject.DestroyResources.UnloadUnusedAssets