System.IO не создает файл json - PullRequest
0 голосов
/ 01 февраля 2019

System.IO не создает файл с сохранением игры.Я пытаюсь запустить Unity в режиме администратора и ничего.

Журнал отладки:

FileNotFoundException: Could not find file "C:\Users\HP\AppData\LocalLow\NameName\BeautyGame\gamesettings.json"
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at <ac823e2bb42b41bda67924a45a0173c3>:0)
System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options, System.String msgPath, System.Boolean bFromProxy, System.Boolean useLongPath, System.Boolean checkHost) (at <ac823e2bb42b41bda67924a45a0173c3>:0)
(wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions,string,bool,bool,bool)

И код:

string jsonData = JsonUtility.ToJson(gameSettings, true);
File.WriteAllText(Application.persistentDataPath + "/gamesettings.json", jsonData));

1 Ответ

0 голосов
/ 04 февраля 2019

Я бы порекомендовал использовать FileStream и StreamWriter и убедиться, что FileMode.Create установлено.Также создайте папку, если она не существует.

var folderPath = Application.persistentDataPath;

// Create directory if not exists
if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
}

Чем использовать Path.Combine для создания строк пути, которые не зависят от системы

var filePath = Path.Combine(folderPath, "gamesettings.json");

Теперь запишите файл

// Create file or overwrite if exists
using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    using (var writer = new StreamWriter(file, Encoding.UTF8))
    {
        writer.Write(content);
    }
}

Однако для тестирования локального на ПК из UnityEditor я бы не хотел, чтобы приложение пропускало данные на мой компьютер для разработки, а вместо этого поместил бы его где-нибудь, например, в StreamingAssets и только в сборке, используя persistentDataPath

var folderPath =
#if !UNITY_EDITOR
     Application.persistentDataPath;
#else
     Application.streamingAssetsPath;
#endif
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...