Write data to Unity's recommended folder path specified by persistentDataPath

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2021.3.3f1
Input System Package
  • 1.3.0

Prerequisites for this tip

The following settings have been made in advance as a premise for the description of this tip.

At first

In the previous tips, PlayerPrefs we used the method of saving and loading data. However, this is not suitable for use from the viewpoint of handling huge data and data sharing.

This time, we will save and load data to the local folder directory. Basically, you can specify the writing location freely, but it is more advantageous to use the specified persistentDataPath in Unity, so this time we will use this.

UI placement and handling

For this, we will use the previous tip "Read and write data using PlayerPrefs" as it is, so Please refer to that and implement it to the point where you can perform button processing.

Incidentally, I will also place a place to display the value of to be used persistentDataPath this time.

Check where the folder path is to save the file

You can get the Application.persistentDataPath folder path of the data to be used this time with . First, let's show where the location is.

Start Let's create a method to display a value in a text field.

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonEvent : MonoBehaviour
{
  // 省略

  /// <summary>パステキスト。</summary>
  [SerializeField] Text TextPath;


  /// <summary>最初に一度だけ呼ばれます。</summary>
  private void Start()
  {
    TextPath.text = Application.persistentDataPath;
  }

  // 省略
}

When you run it, you should see the path on the underside.

Since we are running on Windows this time, the path looks like this. Please note that the contents of the path may change depending on the executing user and "CompanyName" or "ProductName" in the project settings. When creating a game, decide on "CompanyName" and "ProductName" before the game is released and do not change it later.

This path depends on the platform you are running on. Below is the path listed on the official website. It may change depending on your version of Unity, so be sure to run it and check it out.

Save the value

As long as you decide on the destination path, writing and reading data can be handled by the .NET standard library. This time, we are combining the data into one class and writing strings in JSON and writing strings in bulk.

using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class ButtonEvent : MonoBehaviour
{
  // 省略

  /// <summary>セーブデータ。</summary>
  public class SaveData
  {
    public string Name;
    public string HP;
    public string Attack;
    public string Money;
  }

  /// <summary>
  /// 保存ボタンをクリックしたときの処理。
  /// </summary>
  public void OnClickSave()
  {
    // 保存するデータを作成
    var data = new SaveData()
    {
      Name = InputFieldName.text,
      HP = InputFieldHP.text,
      Attack = InputFieldAttack.text,
      Money = InputFieldMoney.text,
    };

    // オブジェクトを JSON 文字列にシリアライズ
    var json = JsonUtility.ToJson(data);

    // 所定の場所にテキストファイルとして保存
    File.WriteAllText(Path.Combine(Application.persistentDataPath, "SaveData.txt"), json);

    Debug.Log("保存しました。");
  }

  // 省略
}

The contents of the previous tips are supported by the .NET Standard Library, so I don't think there is anything particularly difficult. Let's run it first and save it.

If you look at the path location, you will see that the file is saved.

When you open the text file, you can see that your input is saved in JSON format.

We are using a class so that we can File easily write files this time,StreamWriter but there is no problem if we use other classes such as .

Get a saved value

I don't think it's difficult to read either.

/// <summary>
/// 読み込みボタンをクリックしたときの処理。
/// </summary>
public void OnClickLoad()
{
  // 保存されているテキストファイルを読み込む
  var json = File.ReadAllText(Path.Combine(Application.persistentDataPath, "SaveData.txt"));

  // JSON テキストから指定したオブジェクトにデシリアライズ
  var data = JsonUtility.FromJson<SaveData>(json);

  // 読み込んだ値を各フィールドにセット
  InputFieldName.text = data.Name;
  InputFieldHP.text = data.HP;
  InputFieldAttack.text = data.Attack;
  InputFieldMoney.text = data.Money;

  Debug.Log("読み込みました。");
}

You can read the saved text and deserialize the JSON string with the JsonUtility.FromJson method to restore it.

Try running the game and seeing that the input field is populated by clicking the Load from empty button.

Summary

Application.persistentDataPath I was able to read and write data to the specified location using . It can be saved as a file, so it is also possible to store huge data. However, data stored in this folder path may be synchronized in multiple environments, so If you assume that, you should consider whether to save a large file or to save it in another location.