9
9

More than 5 years have passed since last update.

Unityでローカルストレージ

Posted at

ローカルにjsonを書き込んだり、読み込んだりするための簡単なメモ書き。

ローカルストレージへのパスを取得

string savePath = Application.persistentDataPath;

ディレクトリがあるか無いか調べる

Directory.Exists ("パス");

ディレクトリ作成

Directory.CreateDirectory("パス");

読み込み

File.ReadAllText("パス" + "ファイル名.txt");

書き込み

File.WriteAllText("パス" + "ファイル名.txt", json);

簡単なサンプルコード

using UnityEngine;
using System.Collections;
using System.IO;

public class LocalStorage : MonoBehaviour 
{
    string myJson = "[{\"NUM\":\"1\",\"TEXT\":\"HELLO\"},{\"NUM\":\"2\",\"TEXT\":\"BONJOUR\"},]";
    string dataName = "data.txt";

    void Start()
    {
        LoadLocalStageData ();
    }

    // ローカルストレージから読み込み
    public void LoadLocalStageData()
    {
        string savePath = GetPath ();

        // ディレクトリが無い場合はディレクトリを作成して保存
        if ( !Directory.Exists (savePath) )
        {
            // ディレクトリ作成
            Directory.CreateDirectory( savePath );
            // ローカルに保存
            SaveToLocal( myJson );
        }
        else
        {
            // ローカルからデータを取得
            string json = LoadFromLocal ();
            Debug.Log (json);
        }
    }

    // 保存
    void SaveToLocal( string json )
    {
        // jsonを保存
        File.WriteAllText( GetPath() + dataName, json );
    }

    // 取得
    string LoadFromLocal()
    {
        // jsonを読み込み
        string json = File.ReadAllText( GetPath() + dataName );

        return json;
    }

    // パス取得
    string GetPath()
    {
        return Application.persistentDataPath + "/AppData/";
    }
}
9
9
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
9
9