カラスの目はよく見るとかわいい

技術系ブログ。Unity、GoogleAppsScript、C#、VisualStudioCodeを中心に投稿しています。

ユーザデータをStreamingAssetsフォルダにjsonファイルとして保存するサンプル

Directoryはエラーになると思うので、ダブルクリックして右クリック-クイックアクションでusingを追加してください。

public static class FileManagerSample
{
    private const string UserDataFilePath = "user_data.json";
    [System.Serializable]
    public class User_Data
    {
        public int highScore = 0;
    }

    public static User_Data LoadUserData()
    {
        if (Directory.Exists(Application.streamingAssetsPath) == false)
        {
            Directory.CreateDirectory(Application.streamingAssetsPath);
        }
        string fullpath = Path.Combine(Application.streamingAssetsPath, UserDataFilePath);
        if (File.Exists(fullpath) == false)
        {
            return new User_Data();
        }
        string json = File.ReadAllText(fullpath);
        if (string.IsNullOrEmpty(json))
        {
            return new User_Data();
        }
        User_Data data = JsonUtility.FromJson<User_Data>(json);
        return data;
    }

    public static void SaveUserData(User_Data data)
    {
        string fullpath = Path.Combine(Application.streamingAssetsPath, UserDataFilePath);
        string json = JsonUtility.ToJson(data);
        File.WriteAllText(fullpath, json);
    }
}