はじめに
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);
}
}
使い方
- メニューの
Assets > Create > Scriptable Objects > GameStateSOからアセットを生成します - インスペクター等でデータを変更し、以下のように任意のタイミングで呼び出します
// インスペクターなどで参照をアタッチしておく
[SerializeField] private GameStateSO _gameState;
// セーブ
void SaveGame() {
_gameState.SaveToPlayerPrefs();
}
// ロード
void LoadGame() {
_gameState.LoadFromPlayerPrefs();
}
結果
問題なく、PlayerPrefsにセーブした内容をロードすると、ScriptableObjectに反映されました。ScriptableObjectでデータ管理して簡単にセーブしたい場合は使えるかもしれません。
JsonUtilityの注意としては、Dictionaryなどが使えないのでデータ設定には気を付ける必要があります。