Unity 获取文件夹下所有图片并转换成贴图或精灵的方法

在Unity应用程序里面,有时候我们需要通过读取外部文件夹中的图片来获取图片资源。

具体我们可以编写一个脚本来实现:

复制代码
using UnityEngine;
using System.IO;
using System.Collections.Generic;

public class ImageLoader : MonoBehaviour
{
    public string folderPath; // 文件夹路径  
    List<Texture2D> textures = new List<Texture2D>();   //用于存放所有图片转换的贴图
    List<Sprite> sprites = new List<Sprite>();  //用于存放所有图片转换的精灵

    List<string> filePaths = new List<string>(); //用于存放所有图片地址

    void Start()
    {
        // 检查文件夹是否存在
        if (Directory.Exists(folderPath))
        {           
            string imgtype = "*.BMP|*.JPEG|*.GIF|*.PNG|*.JPG";
            string[] ImageType = imgtype.Split('|');

            // 获取文件夹下所有图片文件的地址
            for (int i = 0; i < ImageType.Length; i++)
            {
                string[] paths = Directory.GetFiles(folderPath, ImageType[i]);
                for (int j = 0; j < paths.Length; j++)
                {
                    filePaths.Add(filePaths[j]);
                }
            }


            // 把所读取的图片转换成贴图或精灵
            foreach (string path in filePaths)
            {                
                byte[] fileData = File.ReadAllBytes(path);
                Texture2D texture = new Texture2D(1, 1);
                texture.LoadImage(fileData);  //把图片转换成贴图
                textures.Add(texture);  

                //把图片转换成精灵
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
                sprites.Add(sprite);
            }
        }
        else
        {
            Debug.LogError("文件夹不存在或路径错误!");
        }
    }
}

以上是个简单的读取文件图片的脚本,可以轻轻松松读取外部文件夹中的图片资源并转换成贴图或者精灵来使用。

相关推荐
_ZHOURUI_H_24 分钟前
Unity MyFramework 用法说明(二十三):使用 PrefabPoolManager 复用预设实例
unity·游戏引擎·游戏开发·游戏ui·手游开发
冰凌糕2 小时前
Unity3D Shader 法线与基础光照
unity
新手unity自用笔记6 小时前
unity网络基础_1
网络·unity·游戏引擎
谢斯15 小时前
[vscode] 使用unity打开vscode的取消.csproj的显示
ide·vscode·unity
魔术师Dix15 小时前
StartGame:Unity TDD 外部工程指南
学习·游戏·unity·c#·测试驱动开发
hsw8157739432 天前
第10章 软件架构的演化和维护 — 系统架构设计师
unity·系统架构·游戏引擎
tealcwu2 天前
【尝鲜】Unity 6.7alpha版本测试
unity·游戏引擎