You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#/Unity中如何对FileInfo类型的List排序以解决PDF转Texture后页面数组无序问题?

解决Unity中PDF转Texture后页面顺序混乱的问题

兄弟,我一眼就看出问题所在了——你现在获取的文件列表是按字符串默认排序来的,比如"10.jpg"会排在"2.jpg"前面,因为字符串比较是逐字符对比的。咱们只需要把文件名里的数字提取出来,按数值大小排序,就能让页面顺序正常了。

核心解决方案:按文件名中的数字数值排序

直接在你的Linq查询链里加上OrderBy,提取文件名开头的数字并转为整数,以此作为排序依据:

List<FileInfo> info = dir.GetFiles("*.jpg")
    .Where(file => Regex.IsMatch(file.Name, "^[0-9]+"))
    .OrderBy(file => 
    {
        // 提取文件名开头的纯数字部分
        string pageNumStr = Regex.Match(file.Name, "^[0-9]+").Value;
        return int.Parse(pageNumStr);
    })
    .ToList();

修改后的完整代码

我还帮你优化了路径获取(用FullName代替手动拼接,更可靠),你可以直接替换原来的GetPDFPages方法:

public void GetPDFPages() { 
    DirectoryInfo dir = new DirectoryInfo(@"C:\Users\HP\Desktop\TestBookPages\"); 
    List<FileInfo> info = dir.GetFiles("*.jpg") 
        .Where(file => Regex.IsMatch(file.Name, "^[0-9]+"))
        .OrderBy(file => 
        {
            string pageNumStr = Regex.Match(file.Name, "^[0-9]+").Value;
            return int.Parse(pageNumStr);
        })
        .ToList(); 
    Debug.Log("Sorted page count: " + info.Count);
    tmpTexture = new Texture2D[info.Count]; 
    int y = 0; 
    foreach (FileInfo f in info) { 
        tmpTexture[y] = LoadImageFromFile(f.FullName); // 直接用FullName避免路径拼接错误
        bool front = (y & 1) == 0 ? true : false; 
        book.SetPageTexture(tmpTexture[y], y / 2, front); 
        y++; 
    } 
}

public static Texture2D LoadImageFromFile(string filePath) { 
    Texture2D tex = null; 
    byte[] fileData; 
    if (File.Exists(filePath)) { 
        fileData = File.ReadAllBytes(filePath); 
        tex = new Texture2D(2, 2, TextureFormat.RGBA32, false); 
        tex.LoadImage(fileData); 
    } 
    return tex; 
}

额外说明

  • 如果你的PDF页码可能非常大(比如超过int的范围,不过这种情况极少),可以把int.Parse换成long.Parse,兼容更大的数值。
  • 你的Regex已经确保了文件名开头是数字,所以不用担心转换失败的问题;如果后续文件名格式有变化,记得调整Regex或者加个异常处理哦。

内容的提问来源于stack exchange,提问作者Omkar P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:27:32