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

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

相关推荐
平行云12 小时前
Enscape × Paraverse | 从设计到一键发布、网页分享、实时交互的全新体验
unity·ue5·xr·3dsmax·webgl·实时云渲染·云桌面
老朱佩琪!16 小时前
Unity迭代器模式
unity·设计模式·迭代器模式
程序猿多布17 小时前
Unity 多语言系统实现
unity·多语言
CreasyChan18 小时前
Unity中C#状态模式详解
unity·c#·状态模式
鹿野素材屋18 小时前
动作游戏网游:帧同步下的动画同步
unity·游戏引擎
世洋Blog18 小时前
数据驱动与MVC
unity·mvc
WMX101218 小时前
Unity添加近身菜单-MRTK
unity·游戏引擎
在路上看风景1 天前
15. 纹理尺寸是4的倍数
unity
星依网络1 天前
使用LabelImg工具标注数据(游戏辅助脚本开发)
python·游戏引擎·图形渲染·骨骼绑定
AT~1 天前
unity 使用Socket和protobuf实现网络连接
unity·游戏引擎