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("文件夹不存在或路径错误!");
        }
    }
}

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

相关推荐
井队Tell18 小时前
打造高清3D虚拟世界|零基础学习Unity HDRP高清渲染管线(第五天)
学习·3d·unity
yi碗汤园19 小时前
【一文了解】八大排序-插入排序、希尔排序
开发语言·算法·unity·c#·1024程序员节
AA陈超1 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-14 属性菜单 - 文本值行
c++·游戏·ue5·游戏引擎·虚幻
future_studio1 天前
聊聊 Unity(小白专享、C# 小程序 之 联机对战)
unity·小程序·c#
AA陈超2 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-13 属性菜单 - 边框值
c++·游戏·ue5·游戏引擎·虚幻
shandianchengzi2 天前
【记录】Unity|Unity从安装到打开一个Github项目(以我的世界(仿)为例)
unity·c#·游戏引擎·github·我的世界·mc
bb456b2 天前
Snipaste (截图贴图工具) 精准截图 中文免费版
java·工具·贴图
yi碗汤园2 天前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
野奔在山外的猫3 天前
【案例】Unity 平台访问文件浏览器(汇总)
unity
WaWaJie_Ngen3 天前
【OpenGL】模板测试(StencilTest)
c++·算法·游戏·游戏引擎·游戏程序·图形渲染