Version: 6000.3
语言: 中文
资源系统简介
使用 AssetBundles 在运行时加载资产

使用资源系统加载和卸载资产

要使用资源系统加载资产:

  1. 创建一个名为Resources,然后向其添加资产。然后,Unity 使这些资产可用,即使它们没有在场景场景包含游戏的环境和菜单。将每个唯一的场景文件视为一个独特的关卡。在每个场景中,你放置你的环境、障碍物和装饰品,基本上是将你的游戏设计和构建成碎片。更多信息
    请参阅术语表
    .注意:您可以拥有多个Resources文件夹位于Assets文件夹,包也可以包含Resources文件夹。
  2. 每当您想要从这些文件夹之一加载资产时,请调用Resources.Load在您的代码中。只有Resources可以通过这种方式访问文件夹。

例如,您可以应用以下脚本来加载纹理并将其应用到其中:

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 将所有资产存储在Resources文件夹及其依赖项,并将其依赖项放在名为resources.assets.如果构建中的场景引用了资产,Unity 会将该资产序列化为sharedAssets*.assets文件。

其他资产可能最终出现在resources.assets文件,如果它们是依赖项。例如,在Resources文件夹可能会引用Resources文件夹。在这种情况下,纹理也包含在resources.assets文件,但无法直接加载。

卸载资产

如果要销毁Resources.Loadloaded 之前加载另一个场景,调用Object.Destroy在他们身上。要恢复未引用对象使用的内存,请使用Resources.UnloadUnusedAssets.

其他资源

资源系统简介
使用 AssetBundles 在运行时加载资产