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

Unity项目打包后Directory.CreateDirectory创建目录不生效问题

问题描述

Unity项目中调用Directory.CreateDirectory方法创建目录时,在编辑器内启动运行功能正常,完成打包构建后该功能无法生效,原实现代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

public class FileTool : MonoBehaviour
{
    public string folderName = "name";
    public string path = Environment.CurrentDirectory;
    public string fullPath;

    public void CreateFolder()
    {
        fullPath = Path.Combine(path, folderName);
        Debug.Log(fullPath);
        if (!Directory.Exists(fullPath))
        {
            Directory.CreateDirectory(fullPath);
        }
    }
}
根本原因

问题出在路径获取逻辑上,Environment.CurrentDirectory获取的是程序当前的工作目录,这个值在不同运行环境下的指向和权限差异极大:

  • 编辑器运行时,工作目录默认是Unity项目的根目录,该目录默认开放读写权限,因此创建目录操作可以正常执行
  • 打包后运行时,工作目录的指向完全不受代码控制:
    • Windows端大概率指向exe所在的安装目录,如果安装在Program Files等系统受保护路径下,普通运行权限没有写入资格,创建目录会直接失败
    • Android、iOS等移动端,应用安装目录本身是只读属性,完全不支持写入操作
    • 部分平台启动时会被系统修改工作路径,根本不是代码预期的可写位置
修复方案

不要使用Environment.CurrentDirectory作为文件写入的根路径,直接调用Unity官方提供的、全平台做过权限适配的路径API:

  • 需要长期持久化存储、应用卸载前不会被清理的文件(用户配置、存档、下载的资源等),使用Application.persistentDataPath作为根目录
  • 仅做临时缓存、应用关闭后可丢弃的文件,使用Application.temporaryCachePath作为根目录

修复后的代码参考:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

public class FileTool : MonoBehaviour
{
    public string folderName = "name";
    // 按需替换为Application.temporaryCachePath即可使用临时缓存路径
    public string path = Application.persistentDataPath;
    public string fullPath;

    public void CreateFolder()
    {
        fullPath = Path.Combine(path, folderName);
        Debug.Log($"目标创建路径:{fullPath}");
        if (!Directory.Exists(fullPath))
        {
            Directory.CreateDirectory(fullPath);
        }
    }
}

补充说明:上述两个Unity路径API已经完成全平台适配,不需要自行编写平台分支判断路径,各平台默认都开放对应目录的读写权限:

  • Windows端:persistentDataPath默认指向C:\Users\当前用户名\AppData\LocalLow\项目配置的公司名\项目名
  • Android端:指向应用私有存储目录,不需要额外申请存储权限即可正常读写
  • iOS端:指向应用沙盒内的Documents目录,符合苹果商店的文件存储规范
  • Mac端:指向~/Library/Application Support/项目配置的公司名/项目名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:27:25