Saving a json file in resource folder

Hello Fellow Developers,

There is a very peculiar problem that I am facing. The code part as under is what I am using to save my Item Info in a JSON file (I am Using SimpleJSON for JSON operation).

My information file is getting saved but the changes are not reflected in the file till I minimize unity editor and reopen it again.

public void SaveItemInfo()
	{
          string str = ItemInfo.ToString();
          using (FileStream fs = new FileStream("Assets/Resources/GameJSONData/ItemInfo.json", FileMode.Create))
          {
                   using (StreamWriter writer = new StreamWriter(fs))
		        {
			      writer.Write(str);
			      writer.Close();
			      writer.Dispose();
		        }
			fs.Close();
			fs.Dispose();
		}
	}

I know this sounds weird, I will try to explain the situation with a scenario.
I make an in-game purchase and save the purchase info in a JSON file. When I launch the game next time I should the see the purchased item in my inventory but I do not see the changes. [No Changes made] But when I minimize Unity Editor and relaunch the game I get expected results.

You need to refresh the Editor so that the new item is considered. Qlso you do not need to call Dispose and Close as it is implied in the using(object) statement:

public void SaveItemInfo(){
    string path = null;
    #if UNITY_EDITOR
    path = "Assets/Resources/GameJSONData/ItemInfo.json";
    #endif
    #if UNITY_STANDALONE
        // You cannot add a subfolder, at least it does not work for me
        path = "MyGame_Data/Resources/ItemInfo.json"
    #endif
 
    string str = ItemInfo.ToString();
    using (FileStream fs = new FileStream(path, FileMode.Create)){
        using (StreamWriter writer = new StreamWriter(fs)){
            writer.Write(str);
        }
    }
    #if UNITY_EDITOR
	UnityEditor.AssetDatabase.Refresh ();
    #endif
}

You also need to add the using UnityEditor; at the top. The directive is necessary since that won’t do in the final build.

You may consider saving using PlayerPrefs. It is basically the same as writing into the text file and store on the client.

However when it comes to purchases, it would be better to have a server to store the information somewhere. Storing purchases or sensitive information on client is:

  • Not secured and can be easily hacked.
  • Players may uninstall the game and reinstall them, which will cause them to lose their purchased items

:slight_smile: