LoginSignup
10
7

More than 3 years have passed since last update.

UnityでAndroidの内部ストレージにファイルを保存する

Last updated at Posted at 2020-09-01

コード

using System.IO;

    public static DirectoryInfo SafeCreateDirectory(string path)
    {
        //ディレクトリが存在しているかの確認 なければ生成
        if (Directory.Exists(path))
        {
            return null;
        }
        return Directory.CreateDirectory(path);
    }

    public void Score_Save(string Directory_path,string date)
    {
        //データの保存
        SafeCreateDirectory(Application.persistentDataPath + "/" + Directory_path);
        string json = JsonUtility.ToJson(date);
        Writer = new StreamWriter(Application.persistentDataPath + "/" + Directory_path + "/date.json");
        Writer.Write(json);
        Writer.Flush();
        Writer.Close();
    }

    public Score Score_Load(string Directory_path)
    {
        //データの取得
        var reader = new StreamReader(Application.persistentDataPath + "/" + Directory_path  + "/date.json");
        string json = reader.ReadToEnd();
        reader.Close();
        return json;//使いやすいように変換してください
    }

はじめに

そもそも論としてAndroidには他のアプリと共有できる共有ストレージやそのアプリケーションのみで使用できる内部ストレージなどがある

種類 内容
アプリ固有のストレージ アプリ専用のファイルを、内部ストレージ ボリューム内の専用ディレクトリ、または外部ストレージ内の別の専用ディレクトリに保存します。他のアプリがアクセスできない機密情報の保存には、内部ストレージ内のディレクトリを使用します。
共有ストレージ メディアやドキュメントなど、アプリが他のアプリと共有するファイルを保存します。
設定 非公開のプリミティブ データを Key-Value ペアで保存します。
データベース Room 永続ライブラリを使用して、構造化データを非公開のデータベースに保存します。

・データ ストレージとファイル ストレージの概要

getFilesDir() または getCacheDir()にUnity上でアクセスできれば保存できるっぽい

Unityだと

Application.persistentDataPathをつかえばいい感じにアプリ固有ストレージのパスの取得ができるらしい
ちなみにiosやwindwosの内部ストレージにもこれでいける

ちなみにApplicationでアプリケーション系の処理ができるので気になったら読んでみてもいいと思う

Application.persistentDataPath

結局Application.persistentDataPathは何なの?

A.内部ストレージのパスを返してくれる関数

using System.IO;

StreamWriter Writer = new StreamWriter(Application.persistentDataPath + "任意のファイルパス");
Writer.Write("任意のデータ");
Writer.Flush();
Writer.Close();

で保存ができる

using System.IO;

var reader = new StreamReader(Application.persistentDataPath + "任意のファイルパス");
string string = reader.ReadToEnd();

読み取りはこっち

10
7
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
10
7