如何为JSON文件创建唯一名称



我正在我的Unity游戏中写出一个JSON文件,但是当我玩游戏时,文件" Shader.json"会被新数据覆盖。

我想知道如何将时间戳或增加数字附加到文件路径上,以便每次编写数据时都会创建一个新的JSON文件。

这是我输出JSON数据的代码。编辑和工作

public class writejson : MonoBehaviour
{
public ShaderValues shader = new ShaderValues("Test123", 2, 155, 100, 30);
JsonData shaderJson;
public static string GetUniqueIdentifier()
{
    return System.Guid.NewGuid().ToString();
}

void Start()
{
    shaderJson = JsonMapper.ToJson(shader);
    Debug.Log(shaderJson);
    File.WriteAllText(Application.dataPath + "/Json/ShaderSettings_" + GetUniqueIdentifier() + ".json", shaderJson.ToString());
}

public class ShaderValues
{
    public string name;
    public int shadertype;
    public int red;
    public int blue;
    public int green;

public ShaderValues(string name, int shadertype, int red, int blue, int green)
{
    this.name = name;
    this.shadertype = shadertype;
    this.red = red;
    this.blue = blue;
    this.green = green;
           }
        }
   } 

生成唯一值的简单安全方法是使用 Guid

File.WriteAllText(Application.dataPath + "/Json/Shader"+ Guid.NewGuid().ToString() +".json", shaderJson.ToString());

NewGuid()方法将产生一个新的独特价值,实际上保证不仅在计算机上,而且在世界范围内都是唯一的。

来自Microsoft文档中的Guid页面:

GUID是一个128位整数(16个字节(,可以在所有计算机和网络中使用,无论需要在任何地方使用唯一的标识符。这样的标识符被复制的可能性很低。

用人类的角度,这意味着超过3.4028e 38可能的GUID值 - 在此之后的38位数字。

这里最大的优势是,即使您运行了程序的多个实例,并且每个实例上都有多个线程,每个保存文件,生成相同文件名的机会实际上是0( is 可能,机会很低(。

最新更新