Json Saving For Mobile

I am working on a project in Unity where I have to save data using Json. I save data for levels in Json files and I let the player create their own levels and that gets saved to Json files as well. However, when I run the project on my phone (using xcode) none of the json files from the project show up. In addition, when the user tries to save his own level this error pops up in xcode: IsolatedStorageException: Could not find a part of the path. Also, this error is shown: (Filename: currently not available on il2cpp Line: -1)

I assume you have verified that the JSON you create is valid and can be saved. The next question is, where do you store it? The place you should be storing it is the documents directory, one of the few places you can actually write to in a running app. (library/caches is another - but anything here can be deleted if your device runs short of storage). So how are you creating that path, are you checking for an error during the entire process right down to the write, and are you able to examine the simulator and see that files have been created?

Yes, the Json created saves perfectly fine when I run it in the unity editor. How would I write to the documents directory from Unity? This is the code I use for saving the level:
> var lR = new LevelRepresentation();
lR.waves = waves.ToArray();
lR.startMoney = (int)moneySlider.value;
var levelDataToJson = JsonUtility.ToJson(lR);
var savePath = System.IO.Path.Combine(Application.dataPath + “/PlayerLevels”, nameOfLevelInput.text + “.json”);
System.IO.File.WriteAllText(savePath, levelDataToJson);
Debug.Log ("Level saved to " + savePath);
In my Unity project, I have a folder for the Player levels (Hence the Application.dataPath + “/PlayerLevels”). Maybe when exported to Xcode, this folder doesn’t exist anymore so I have to take that part away?

Hmm - .Net? Kind of outside what I know. But I have had a look at the WriteAllText method and it looks like there is no return value - how can you know whether it succeeded or not? Is there a variant that does return a status? What is Application.dataPath? Perhaps that is already the data directory.

Hey @tobyfutbol

For mobile devices (it works on PC/Mac too though) you’ll want to use Application.persistentDataPath instead of Application.dataPath.
Here’s the documentation on this: https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html

Cheers!

Thanks @blackdragonbe. Using Application.persistentDataPath solved my problems!

1 Like

Looks like you have some domain experience - thanks!