はじめに
通常、EditorWindowのパラメータはウィンドウを閉じてしまうとリセットされてしまいます。
ウィンドウ上のパラメータをScriptableObjectに保存しておくことで、ウィンドウを閉じた後でもデータを保持させておくことができます。
今回はそのやり方についてご紹介したいと思います。
環境
Windows 10
Unity5.6.1f1
STEP1. ScriptableObjectクラスの用意
今回はEditorWindowへ入力したテキストを永続化するという例を考えます。
まずはデータ保存用にScriptableObjectクラスを作成します。
以下のスクリプトをプロジェクト内へ入れてください.
namespace PermanentTest
{
using UnityEngine;
[CreateAssetMenu]
public class PermanentData : ScriptableObject
{
[SerializeField] private string text;
public string Text { get { return this.text; } set { this.text = value; } }
}
}
[SerializeField]をつけたstring変数と、その読み書きを行うプロパティを定義しただけのシンプルなScriptableObjectクラスです。
[CreateAssetMenu]をつけることでメニューからScriptableObjectアセットを作成できるようにしています。
STEP2. ScriptableObjectの作成
Projectウィンドウ上で右クリックして、Create -> Permanent Data を選択してScriptableObjectを作成します。
STEP3. EditorWindowの用意
プロジェクト内にEditorフォルダを作成して、以下のスクリプトをフォルダの中へ入れます。
namespace PermanentTest
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
public class PermanentEditorWindow : EditorWindow
{
[SerializeField] private PermanentData data; // データ
[MenuItem("EditorWindow/PermanentEditorWindow")]
static void Open()
{
GetWindow<PermanentEditorWindow>(); // ウィンドウを開く
}
/// <summary>
/// ウィンドウの描画
/// </summary>
void OnGUI()
{
if (this.data == null) { this.data = LoadData(); }
EditorGUI.BeginChangeCheck();
string text = this.data.Text; // ScriptableObjectからテキストを取り出す
text = EditorGUILayout.TextField("テキスト", text); // テキスト入力
if (EditorGUI.EndChangeCheck()) // テキストが変更された場合は
{
this.data.Text = text; // データへテキストを保存する
EditorUtility.SetDirty(this.data); // データの変更をUnityに教える
}
}
/// <summary>
/// データのロード
/// </summary>
static PermanentData LoadData()
{
return (PermanentData)AssetDatabase.FindAssets("t:ScriptableObject") // プロジェクトに存在する全ScriptableObjectのGUIDを取得
.Select(guid => AssetDatabase.GUIDToAssetPath(guid)) // GUIDをパスに変換
.Select(path => AssetDatabase.LoadAssetAtPath(path, typeof(PermanentData))) // パスからPermanentDataの取得を試みる
.Where(obj => obj != null) // null要素は取り除く
.FirstOrDefault(); // 取得したPermanentDataのうち、最初の一つだけを取り出す
}
}
}
ScriptableObjectの自動ロードを行い、入力テキストをScriptableObject内へ保存しています。
STEP4. テキストが永続化していることを確認する。
画面上部のメニューから EditorWindow -> PermanentEditorWindow を選択して、ウィンドウを開きます。
ウィンドウをいったん閉じて開きなおしてもテキストは入力されたままだということが確認できます。
※ScriptableObjectが存在しない場合はエラーが出てしまうので注意してください
テキストの保存先について
ScriptableObjectを確認すると、ウィンドウ上のテキストが保存されていることが確認できます。