LoginSignup
5
5

More than 3 years have passed since last update.

【Unity】iOSでセーブデータを読み書きする

Last updated at Posted at 2020-02-10

概要

UnityでiPhoneの実機テストをした時に
ファイルの読み書きにつまづいたのでメモを残します。

環境

Unity 2019.2.10f1
Xcode ver.11.3.1
iOS 13.2

サンプル

データ

[System.Serializable]
public class SaveData
{
    public int stageNum = 3;
    public int[] score = new int[stageNum];
}

jsonなので配列も扱えますね。

セーブ

    public void Save(SaveData data){
        StreamWriter writer;
        string jsonData = JsonUtility.ToJson(data);

        writer = new StreamWriter(Application.persistentDataPath + "/savedata.json", false);
        writer.Write (jsonData);
        writer.Flush ();
        writer.Close ();
    Save(data);

pathにはApplication.persistentDataPathを使います。
StreamingAssetsは読み込み専用なのでセーブデータには適しません。
逆にアプリから書き換えることのないステージ情報などはStreamingAssetsを使うのが良いと思います。
・参考
StreamWriterの第二引数はtrueで追記、falseで上書きとなります。

ロード


    public SaveData Load(){
        string data = "";
        StreamReader reader;

        reader = new StreamReader(Application.persistentDataPath + "/savedata.json");
        data = reader.ReadToEnd ();
        reader.Close ();

        return JsonUtility.FromJson<SaveData>(datastr);
    }
    SaveData data = Load();
    print(data.score[0]);

リセット


    public void ResetData(){
        // 初期状態のデータをセーブ
        SaveData data = new SaveData();
        Save(data);
    }
    ResetData();

初回起動のとき

    void Start() {
        if (System.IO.File.Exists(Application.persistentDataPath + "/savedata.json") == false) {
            ResetData();
        }   
    }

jsonデータがないときにデータを作成します。
開発の段階であらかじめpersistentDataPathにjsonファイルを置いておくことはできません。

終わりに

iOS以外のプラットフォームでは処理を分ける必要がある場合があります。
間違い等あればご指摘願います。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5