1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】JsonUtilityを使ってScriptableObjectのデータをPlayerPrefsにセーブ・ロードする

1
Posted at

はじめに

UnityドキュメントのJsonUtilityのページで、JsonUtilityでJsonにしたデータをPlayerPrefsに保存するサンプルがあります。これを見たときに、ScriptableObjectsをJsonに変換すれば、そのままPlayerPrefsに保存できるなと思い、実際にやってみました。

作成したコード

using UnityEngine;
using System.Collections.Generic;

[CreateAssetMenu(fileName = "GameStateSO", menuName = "Scriptable Objects/GameStateSO")]
public class GameStateSO : ScriptableObject
{
    public int Lives;
    public int Level;
    public string CharacterName;
    public List<string> ItemsCarried;
 
    public const string PlayerPrefsKeyName = "SavedGameState";

    public void SaveToPlayerPrefs()
    {
        // Convert this GameStateSO instance to a JSON string
        string json = JsonUtility.ToJson(this);

        // Save the converted JSON into the PlayerPrefs
        PlayerPrefs.SetString(PlayerPrefsKeyName, json);
        PlayerPrefs.Save();
    }

    public void LoadFromPlayerPrefs()
    {
        // If the game was never saved before, the key will not exist; in this case return
        if(!PlayerPrefs.HasKey(PlayerPrefsKeyName))
            return;

        // Retrieve the saved JSON string from the player prefs
        string json = PlayerPrefs.GetString(PlayerPrefsKeyName);

        // Deserialize the JSON string into this GameStateSO object
        JsonUtility.FromJsonOverwrite(json, this);
    }
}

使い方

  1. メニューの Assets > Create > Scriptable Objects > GameStateSO からアセットを生成します
  2. インスペクター等でデータを変更し、以下のように任意のタイミングで呼び出します
// インスペクターなどで参照をアタッチしておく
[SerializeField] private GameStateSO _gameState;

// セーブ
void SaveGame() {
    _gameState.SaveToPlayerPrefs();
}
// ロード
void LoadGame() {
    _gameState.LoadFromPlayerPrefs();
}

結果

問題なく、PlayerPrefsにセーブした内容をロードすると、ScriptableObjectに反映されました。ScriptableObjectでデータ管理して簡単にセーブしたい場合は使えるかもしれません。

JsonUtilityの注意としては、Dictionaryなどが使えないのでデータ設定には気を付ける必要があります。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?