首页 > 解决方案 > UnauthorizedAccessException:将统一数据保存到文件时访问路径

问题描述

我有一个库存系统,它保存在一个文件中,并在需要时从同一个文件中加载。问题是加载系统在启动时完美运行但是当我按下保存和退出按钮时,它应该保存库存并加载主菜单场景,它会抛出 UnauthorizedAccessException: Access to the path 异常,即使文件未设置为只读,并且加载和保存的savePath相同:

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();
    }
}

启动功能:

private void Start()
{
    LoadInventory();
}

private void LoadInventory()
{
    inventory.Load();
    equipment.Load();
}

保存功能:

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();
}

以及调用保存函数的位置。构建游戏时 SceneManager.LoadScene(0); 行不运行:

public void SaveAndExit()
{
    Time.timeScale = prevTimeScale;
    SaveInventory();

    SceneManager.LoadScene(0);
}

private void SaveInventory()
{
    inventory.Save();
    equipment.Save();
}

检查器中的 savePath 值

在此处输入图像描述


奇怪的是,如果我构建游戏,库存从文件中正确加载,如果我尝试保存并退出,游戏会引发错误,但数据仍然正确保存在文件中。我觉得我在这里遗漏了一些非常明显的东西。如果您需要更多信息,请随时询问。

标签: c#unity3d

解决方案


推荐阅读