You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过脚本在Unity中从Assets文件夹取图片添加到Hierarchy

从任意Assets路径加载图片并实例化到Hierarchy的方案

针对你不想局限于Resources文件夹的需求,下面是几种更灵活的实现方式,同时支持重复执行:

1. 编辑器模式下用AssetDatabase(仅在Unity编辑器中生效)

如果你只需要在编辑器内重复执行这个操作,AssetDatabase是最直接的选择,它可以访问Assets下任意路径的资源:

using UnityEngine;
using UnityEditor;

public class LoadImageEditor : EditorWindow
{
    // 可在编辑器面板中指定图片路径
    private string imagePath = "Assets/Images/MyImage.png";

    [MenuItem("Tools/加载并实例化图片")]
    public static void ShowWindow()
    {
        GetWindow<LoadImageEditor>("图片加载工具");
    }

    private void OnGUI()
    {
        imagePath = EditorGUILayout.TextField("图片路径", imagePath);
        
        if (GUILayout.Button("执行加载"))
        {
            LoadAndInstantiateImage(imagePath);
        }
    }

    private void LoadAndInstantiateImage(string path)
    {
        // 从指定路径加载Texture2D
        Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
        if (texture == null)
        {
            Debug.LogError("找不到指定路径的图片:" + path);
            return;
        }

        // 创建RawImage显示图片(也可以用SpriteRenderer等)
        GameObject imageObj = new GameObject("LoadedImage");
        RawImage rawImage = imageObj.AddComponent<RawImage>();
        rawImage.texture = texture;
        // 调整大小适配图片
        imageObj.GetComponent<RectTransform>().sizeDelta = new Vector2(texture.width, texture.height);
    }
}
  • 用法:打开顶部菜单Tools/加载并实例化图片,输入图片的Assets相对路径,点击按钮即可重复执行。
  • 注意:AssetDatabase只能在编辑器中使用,打包后的游戏无法调用。

2. 运行时用Addressable Assets System(推荐用于打包后的游戏)

如果需要在打包后的游戏中也能灵活加载任意路径的资源,Unity的Addressable Assets是最佳方案,它不需要把资源放在Resources文件夹,还支持异步加载:

步骤:

  1. 在Package Manager中安装Addressables包
  2. 选中你要加载的图片,在Inspector面板勾选Addressable,设置一个唯一的地址(比如MyImage)
  3. 编写运行时脚本:
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class AddressableImageLoader : MonoBehaviour
{
    // 可在Inspector中指定图片的Addressable地址
    public string imageAddress = "MyImage";

    public void LoadAndInstantiateImage()
    {
        // 异步加载图片
        Addressables.LoadAssetAsync<Texture2D>(imageAddress).Completed += OnImageLoaded;
    }

    private void OnImageLoaded(AsyncOperationHandle<Texture2D> handle)
    {
        if (handle.Status == AsyncOperationStatus.Succeeded)
        {
            Texture2D texture = handle.Result;
            // 创建显示对象
            GameObject imageObj = new GameObject("AddressableImage");
            RawImage rawImage = imageObj.AddComponent<RawImage>();
            rawImage.texture = texture;
            imageObj.GetComponent<RectTransform>().sizeDelta = new Vector2(texture.width, texture.height);
            
            // 释放资源(如果不需要长期持有)
            Addressables.Release(handle);
        }
        else
        {
            Debug.LogError("加载图片失败:" + handle.OperationException);
        }
    }
}
  • 重复执行:给按钮绑定LoadAndInstantiateImage方法,点击即可重复加载实例化。
  • 优势:支持远程资源更新、异步加载避免卡顿,完全摆脱Resources的路径限制。

3. 用ScriptableObject管理资源路径(适合固定资源集合)

如果你的图片是固定的一批,不想每次输入路径,可以用ScriptableObject统一管理:

using UnityEngine;

[CreateAssetMenu(fileName = "ImageCollection", menuName = "创建图片集合")]
public class ImageCollection : ScriptableObject
{
    public Texture2D[] images;
}

然后在脚本中引用这个ScriptableObject,循环或选择加载:

using UnityEngine;
using UnityEngine.UI;

public class BatchImageLoader : MonoBehaviour
{
    public ImageCollection imageCollection;

    public void InstantiateRandomImage()
    {
        if (imageCollection == null || imageCollection.images.Length == 0)
        {
            Debug.LogError("未指定图片集合");
            return;
        }

        // 随机选一张图片(也可以按索引选择)
        Texture2D texture = imageCollection.images[Random.Range(0, imageCollection.images.Length)];
        GameObject imageObj = new GameObject("BatchLoadedImage");
        RawImage rawImage = imageObj.AddComponent<RawImage>();
        rawImage.texture = texture;
        imageObj.GetComponent<RectTransform>().sizeDelta = new Vector2(texture.width, texture.height);
    }
}
  • 用法:右键创建创建图片集合的ScriptableObject,把要加载的图片拖进去,在脚本中引用这个对象,绑定按钮执行方法即可重复操作。

内容的提问来源于stack exchange,提问作者Ashkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:53:10