Unity读取文件夹中所有的图片显示在Iamge组件上
时间: 2025-06-29 13:00:10 浏览: 16
### 实现读取指定文件夹内的所有图片并显示在 Image 组件上的方法
为了实现在 Unity 中读取指定文件夹中的所有图片并将这些图片显示在 `Image` 组件上,可以采用以下方案。此过程涉及到了文件路径处理、资源加载以及 UI 元素更新等内容。
#### 准备工作
确保目标图片放置于特定文件夹中,例如将图片置于项目的 `StreamingAssets` 文件夹下[^3]。对于 Android 或其他平台,可能需要考虑不同平台间路径差异带来的影响。
#### 编写C#脚本逻辑
下面给出一段用于遍历给定目录下的所有图像文件,并将其逐一呈现至场景中存在的 `RawImage` 或者 `Image` 控件上的 C# 脚本实例:
```csharp
using UnityEngine;
using System.IO;
using UnityEngine.UI;
public class LoadImagesFromFolder : MonoBehaviour
{
public string folderPath; // 设置为 "jar:file://" + Application.dataPath + "!/assets/" 对应Android平台
// PC端可直接设为Application.streamingAssetsPath
private Sprite[] sprites;
void Start()
{
LoadAllSprites();
DisplaySprite(0);
}
/// <summary>
/// 加载全部精灵图
/// </summary>
void LoadAllSprites()
{
List<Sprite> spriteList = new List<Sprite>();
foreach (string file in Directory.GetFiles(folderPath, "*.jpg"))
{
byte[] bytes = File.ReadAllBytes(file);
Texture2D texture = new Texture2D(2, 2);
if (!texture.LoadImage(bytes))
continue;
Rect rect = new Rect(0.0f, 0.0f, texture.width, texture.height);
Vector2 pivot = new Vector2(0.5f, 0.5f);
Sprite sprite = Sprite.Create(texture, rect, pivot);
spriteList.Add(sprite);
}
sprites = spriteList.ToArray();
}
/// <summary>
/// 展示索引对应的精灵图
/// </summary>
/// <param name="index"></param>
public void DisplaySprite(int index)
{
GameObject imageObject = GameObject.FindWithTag("MainCamera").transform.GetChild(index).gameObject;
if(imageObject != null && index >= 0 && index < sprites.Length){
RawImage rawImg = imageObject.GetComponent<RawImage>();
if(rawImg!=null){
rawImg.texture = sprites[index].texture;
}else{
Image imgComponent = imageObject.GetComponent<Image>();
if(imgComponent!=null){
imgComponent.sprite = sprites[index];
}
}
}
}
}
```
上述代码实现了从设定好的文件夹位置加载所有 `.jpg` 类型的图片文件作为纹理数据,并创建相应的 `Sprite` 对象存储起来;之后通过调用 `DisplaySprite()` 方法来切换当前显示的具体哪张图片[^1][^2]。
注意:实际应用时需根据具体需求调整文件扩展名过滤条件(如支持更多格式)、优化性能等方面的工作。
阅读全文
相关推荐













