Unity读取项目文件夹图片命名方式

您好,请问怎么写一个从unity项目内文件夹中读取图片命名传入到UI scrow view中显示文字命名,然后点击scrow view中的文字可以在rawiamge展现图片


您好,Unity读取项目文件夹中的图片并显示在UI ScrollView中,步骤如下:
1. 在Unity项目的Assets文件夹中创建一个图片资源文件夹,将需要显示的图片拷贝到这个文件夹中。
2. 在UI Canvas上创建一个Scroll View组件,作为滚动视图。
3. 在Scroll View下面创建一个Vertical Layout Group组件,用于垂直排列图片。
4. 编写一个C#脚本,在Start()方法中使用Directory.GetFiles()读取图片文件夹内的所有图片文件路径,然后遍历路径使用WWW类加载图片,实例化Image组件显示到Scroll View中。
5. 为每个Image组件添加一个Text组件显示图片名称,图片名称可以直接从路径中提取出来。
6. 为Image组件添加点击事件,在事件中根据Text的图片名称再加载一次图片并显示在另一个RawImage上。
关键代码如下:
// 获取图片路径
string[] paths = Directory.GetFiles(imageFolderPath);

foreach (string path in paths)  
{
  // 从路径提取文件名
  string name = Path.GetFileNameWithoutExtension(path); 

  // 加载图片
  WWW www = new WWW(path);
  Texture2D texture = www.texture;

  // 创建Image显示图片
  GameObject go = Instantiate(imagePrefab); 
  go.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
  
  // 显示图片名称
  go.GetComponentInChildren<Text>().text = name;

  // 加载图片并显示在RawImage上
  go.GetComponent<Button>().onClick.AddListener(() => {
    WWW www2 = new WWW(path); 
    rawImage.texture = www2.texture;
  });

}
这样就可以实现在ScrollView中显示图片名称,点击后在RawImage显示大图了。你可以根据自己的需求调整代码。