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

Unity中如何为JSON文件创建唯一文件名避免覆盖

解决Unity写入JSON时避免覆盖,生成唯一文件名的方案

我来给你两种实用的解决方案,分别用时间戳和递增编号来生成唯一的JSON文件名,彻底解决每次运行游戏覆盖旧文件的问题:

方案一:用时间戳生成唯一文件名(最简单)

时间戳方案的优势是不用处理文件计数逻辑,直接利用当前时间生成唯一文件名,格式比如Shader_20240520_143025.json,精确到秒几乎不会重复。

先补全你的ShaderValues类(必须加序列化标签才能被JsonUtility处理):

[System.Serializable]
public class ShaderValues
{
    public string name;
    public int value1;
    public int value2;
    public int value3;
    public int value4;

    public ShaderValues(string n, int v1, int v2, int v3, int v4)
    {
        name = n;
        value1 = v1;
        value2 = v2;
        value3 = v3;
        value4 = v4;
    }
}

然后修改你的写入逻辑,生成带时间戳的文件:

public class writejson : MonoBehaviour
{
    public ShaderValues shader = new ShaderValues("Test123", 2, 155, 100, 30);

    void Start()
    {
        // 生成精确到秒的时间戳格式
        string timestamp = System.DateTime.Now.ToString("yyyyMMdd_HHmmss");
        // 使用Unity推荐的持久化路径,跨平台兼容
        string filePath = Application.persistentDataPath + $"/Shader_{timestamp}.json";

        // 序列化JSON数据(prettyPrint: true让格式更易读)
        string jsonString = JsonUtility.ToJson(shader, prettyPrint: true);

        // 写入文件
        System.IO.File.WriteAllText(filePath, jsonString);
        Debug.Log($"JSON文件已保存: {filePath}");
    }
}

如果需要更精确的唯一性(比如同秒内多次生成),可以把时间戳格式改成yyyyMMdd_HHmmssfff,其中fff代表毫秒。

方案二:用递增编号生成有序文件名

如果需要按顺序生成Shader_1.json、Shader_2.json这类有序文件,就需要先遍历目录下的现有文件,找到最大编号再加1:

public class writejson : MonoBehaviour
{
    public ShaderValues shader = new ShaderValues("Test123", 2, 155, 100, 30);

    void Start()
    {
        string saveDir = Application.persistentDataPath;
        string filePrefix = "Shader_";
        string fileExt = ".json";

        // 筛选目录下所有符合命名规则的JSON文件
        string[] existingFiles = System.IO.Directory.GetFiles(saveDir, $"{filePrefix}*{fileExt}");

        int maxFileNumber = 0;
        foreach (string file in existingFiles)
        {
            // 提取文件名中的数字部分
            string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
            if (int.TryParse(fileName.Substring(filePrefix.Length), out int currentNumber))
            {
                if (currentNumber > maxFileNumber)
                {
                    maxFileNumber = currentNumber;
                }
            }
        }

        // 生成新的编号文件名
        int newFileNumber = maxFileNumber + 1;
        string newFilePath = System.IO.Path.Combine(saveDir, $"{filePrefix}{newFileNumber}{fileExt}");

        // 序列化并写入
        string jsonString = JsonUtility.ToJson(shader, prettyPrint: true);
        System.IO.File.WriteAllText(newFilePath, jsonString);
        Debug.Log($"JSON文件已保存: {newFilePath}");
    }
}

注意事项

  • 优先使用Application.persistentDataPath:这是Unity官方推荐的持久化存储路径,在Windows、Mac、移动端等所有平台都能正确访问,避免硬编码绝对路径带来的兼容性问题。
  • 序列化要求:使用JsonUtility时,你的数据类必须添加[System.Serializable]标签,否则无法正常序列化。
  • 权限问题:如果在移动端写入文件,确保你的应用有存储权限(Android需要在Manifest中声明,iOS需要在Info.plist中添加权限描述)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:37:14