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

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

相关推荐
Avalon7121 小时前
Unity3D响应式渲染UI框架UniVue
游戏·ui·unity·c#·游戏引擎
风酥糖2 小时前
Godot游戏练习01-第33节-新增会爆炸的敌人
游戏·游戏引擎·godot
ellis19703 小时前
Unity UI性能优化一之插件【Unity UI Optimization Tool】
unity·性能优化
Zik----5 小时前
Unity基础学习笔记(B站视频课整理)
unity·vr
郑寿昌15 小时前
UE5与UE6在Lumen和Nanite的差异解析
游戏引擎·图形渲染·着色器
郝学胜-神的一滴18 小时前
罗德里格斯旋转公式(Rodrigues‘ Rotation Formula)完整推导
c++·unity·godot·图形渲染·three.js·unreal
郑寿昌1 天前
UE6 AI加速Lumen光线追踪降噪技术解析
人工智能·游戏引擎
晴夏。1 天前
GAS下的网络同步的全面分析【超级全面】
游戏引擎·ue·gas·网络同步
田鸡_1 天前
Unity新输入系统(Input System)教学篇
unity·游戏引擎·游戏程序
EQ-雪梨蛋花汤1 天前
【Unity笔记】Unity 音游模板与免费资源:高效构建节奏游戏开发全指南
笔记·unity·游戏引擎