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

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

相关推荐
心之所向,自强不息4 小时前
【Unity Shader编程】之让画面动起来
unity·游戏引擎
不伤欣1 天前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar1 天前
vulkan游戏引擎test文件memory实现
游戏引擎
Magnum Lehar1 天前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
快乐觉主吖1 天前
Unity的日志管理类
android·unity·游戏引擎
WarPigs2 天前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C2 天前
【业务框架】3C-相机-Cinemachine
unity
Tiger Z2 天前
R 语言科研绘图第 55 期 --- 网络图-聚类
开发语言·r语言·贴图
一线灵2 天前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎
高德技术2 天前
全流程开源!高德3D贴图生成系统,白模一键生成真实感纹理贴图
3d·贴图