To load assets with the Resources system:
Resources in your project, and add assets to it. Unity then makes these assets available even if they’re not directly referenced in a scene.Resources.Load or Resources.LoadAsync in your code. Only assets in the Resources folder can be accessed in this way.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.");
}
}
}
Your project can contain any number of Resources folders. To add another Resources folder, create a new folder named Resources anywhere inside your project’s Assets folder or its subfolders, or inside a package. Unity treats every folder with this name as a Resources folder and combines the contents of all of them. Unity doesn’t include Resources folders that are inside an Editor folder in Player builds.
When you load an asset, the path you pass to Resources.Load or Resources.LoadAsync starts from the Resources folder that contains the asset, and doesn’t include the file extension. For example, to load Assets/Resources/Enemies/Goblin.prefab or Assets/Characters/Resources/Enemies/Goblin.prefab, you pass the same path: Enemies/Goblin. If both assets exist, you can’t control which one Unity loads, so give assets in different Resources folders unique paths or names.
Unity stores all assets in the Resources folders and their dependencies in a file in the build output called resources.assets. If a scene in the build references an asset, Unity serializes that asset into a sharedAssets*.assets file instead.
Additional assets might end up in the resources.assets file if they’re dependencies. For example, a material in the Resources folder might reference a texture outside of the Resources folder. In that case the texture is also included in the resources.assets file, but isn’t available to load directly.
If you want to destroy objects that Resources.Load loaded before loading another scene, call Object.Destroy on them. To recover memory used by unreferenced objects, use Resources.UnloadUnusedAssets.