I have a inventory system which is saved in a file and loaded from the same file when its needed. The problem is that the loading system works perfectly on start but when i press the save and exit button, which is supposed to save the inventory and load the main menu scene, it throws a UnauthorizedAccessException: Access to the path exception, even though the file is not set to read-only and the savePath is the same for both loading and saving:
public void Load()
{
if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Open, FileAccess.Read);
Inventory newContainer = (Inventory)formatter.Deserialize(stream);
for (int i = 0; i < container.items.Length; i++)
{
container.items[i].UpdateSlot(newContainer.items[i].item, newContainer.items[i].amount);
}
stream.Close();
}
}
The start function:
private void Start()
{
LoadInventory();
}
private void LoadInventory()
{
inventory.Load();
equipment.Load();
}
The save funtion:
public void Save()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, container);
stream.Close();
}
And where the save function is called. When building the game the SceneManager.LoadScene(0); line doesn't run:
public void SaveAndExit()
{
Time.timeScale = prevTimeScale;
SaveInventory();
SceneManager.LoadScene(0);
}
private void SaveInventory()
{
inventory.Save();
equipment.Save();
}
The savePath value in the inspector
And the strange thing is that if i build the game the inventory loads correctly from file and if i try to save and exit, the game throws an error however the data is still saved correctly on the file. I feel like i am missing something here that is quite obvious. If you need anymore info please feel free to ask.