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

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

相关推荐
点心的游戏开发世界1 小时前
GDScript 入门笔记(五):函数
笔记·游戏引擎·godot
谢斯4 小时前
[unity]如何在unity中添加newtonsoft-json
unity·json·游戏引擎
天人合一peng5 小时前
Unity标记固定颜色及投影标记
unity
云雨巫山8 小时前
Unity 游戏开发性能优化全景手册
unity·智能手机·性能优化·游戏引擎
maybeyaluokenai8 小时前
unity build in渲染管线概述
unity·图形渲染
学习星球8 小时前
AI 原生游戏开发:Godot 4 + AI Agent 全栈指南(Ziva 3 / Godot MCP 深度实战)
人工智能·游戏引擎·godot
云雨巫山9 小时前
Unity 性能优化 · 图解全景手册
unity·性能优化·游戏引擎
Madokaly1 天前
DOTween的Vector3Plugin
unity
Rina GO1 天前
PS怎么把文字贴在圆柱体上?2种实用方法教程附不规则物体贴图
人工智能·贴图·ps插件·不规则物体贴图·文字贴图·ai贴图
点心的游戏开发世界1 天前
GDScript 入门笔记(二):变量与数据类型
笔记·游戏引擎·godot