0

I am writing out a Json file in my unity game, however when I play the game the file "Shader.json" gets overwritten with new data.

I am wondering how I can append a timestamp or a increasing number to the file path so that it creates a new Json file each time the data is written.

Here is my code to output the Json data. Edited and working

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;

           }

        }
   } 
cyo
  • 69
  • 1
  • 14
  • [Append a timestamp to a string in C#](https://stackoverflow.com/questions/7898392/append-timestamp-to-a-file-name?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Foggzie Mar 28 '18 at 17:43

1 Answers1

2

The easy and safe way to generate a unique value is using Guid:

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

The NewGuid() method will generate a new unique value, practically guaranteed to be unique not only on your computer, but world wide.

From the Guid page in Microsoft Docs:

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

In human terms, this means that there are over 3.4028e+38 possible guid values - that's 3 with 38 digits after that.

The biggest advantage here is that even if you run multiple instances of your program, and have multiple threads on each instance, each saving a file, the chance of generating the same file name is practically 0 (It is possible, just very low chance).

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • 2
    Not sure if a guid is the best way to do this. If the files need to be in the correct chronological order, putting a timestamp or an increasing integer, like what OP asked, would make more sense. – Arian Motamedi Mar 28 '18 at 15:38
  • 1
    Nothing is stopping you from sorting the files based on created date.... – Zohar Peled Mar 28 '18 at 15:39
  • @PoweredByOrange - You are correct as I am trying to look at the data in chronological order. But these are all good option and suggestions! – cyo Mar 28 '18 at 17:01