Android Unity C# : Unauthorizedaccessexception Writing Save Game Data
I'm debugging a Unity game in Android, everything works in the Unity editor. I'm receiving an UnauthorizedAccessException when saving the current game data on Android. I am writin
Solution 1:
You have to check if the directory exist with Directory.Exists
before writing to that path. If it does not, use Directory.CreateDirectory
to create it.
Note that it's not a good idea to save file directly to Application.persistentDataPath
. You have to create a folder inside it first then put save your file inside that folder. So Application.persistentDataPath/yourcreatedfolder/yourfile.extension
is fine. By doing this, your code will also work on iOS.
This is what that code should look like:
stringsaveGameFileName="current";
stringfilePath= Path.Combine(Application.persistentDataPath, "data");
filePath = Path.Combine(filePath, saveGameFileName + ".sg");
//Create Directory if it does not existif (!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
}
try
{
BinaryFormatterbf=newBinaryFormatter();
FileStreamfile=newFileStream(filePath, FileMode.Create);
GameDatadata=newGameData(currentGame);
bf.Serialize(file, data);
file.Close();
Debug.Log("Saved Data to: " + filePath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + filePath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
Post a Comment for "Android Unity C# : Unauthorizedaccessexception Writing Save Game Data"