初めに
Unity には、EditorPrefs クラスというエディタの設定情報を保存するときに使用するクラスがあります。本記事では、EditorPrefs クラスの関数の使い方を説明します。
Index
EditorPrefs
EditorPrefs クラスは Unity エディターの設定情報を保存するクラスです。
EditorPrefs を使う意味
例えば、メモを残すために、Text を入力する部分をエディタ拡張をすることを考えます。
上の画像のような TextArea には、文字を入力することができますが、いったん閉じると、白紙に戻ってしまいます。このように Editor 拡張した部分に入力した値を保存、ロードしたい場合に EditorPrefs を用います。
※上のような TextArea を表示し、入力された文章をセーブ、ロードするためのスクリプトは、下記の SetString・GetString の部分に載せています。
SetBool・GetBool
SetBool は key で識別し、Bool 型の値を保存します。GetBool は key を指定し、保存された値を取得します。第2変数はデフォルト値であり、key が存在しない場合にこの値を返します。
public static void SetBool (string key, bool value); public static bool GetBool (string key, bool defaultValue= false);
using UnityEditor; public class ExampleEditorScript { private const string PrefKey = "IsFeatureEnabled"; [MenuItem("MyMenu/Enable Feature")] //機能を有効にする private static void EnableFeature() { EditorPrefs.SetBool(PrefKey, true); //PrefKeyにtrueを保存 } [MenuItem("MyMenu/Disable Feature")] //機能を無効にする private static void DisableFeature() { EditorPrefs.SetBool(PrefKey, false); //PrefKeyにfalseを保存 } [MenuItem("MyMenu/Check Feature Status")] private static void CheckFeatureStatus() //機能の有効, 無効を判定する { bool isFeatureEnabled = EditorPrefs.GetBool(PrefKey, false); //PrefKeyに保存された値の取得 if (isFeatureEnabled) { Debug.Log("Feature is enabled."); } else { Debug.Log("Feature is disabled."); } } }
SetString・GetString
String 型の値を保存、取得する関数です。
public static void SetString (string key , string value ); public static string GetString (string key, string defaultValue= "");
(参考)TextArea を表示、入力、ロードするスクリプト
using UnityEditor; using UnityEngine; public class ExampleEditorScript : EditorWindow { private string textValue; private const string PrefKey = "TextAreaValue"; [MenuItem("Window/My Window")] private static void OpenWindow() { ExampleEditorScript window = GetWindow<ExampleEditorScript>(); window.titleContent = new GUIContent("My Window"); window.Show(); } private void OnEnable() { textValue = EditorPrefs.GetString(PrefKey, string.Empty); } private void OnGUI() { GUILayout.Label("Text Area Example", EditorStyles.boldLabel); textValue = EditorGUILayout.TextArea(textValue, GUILayout.Height(100)); if (GUILayout.Button("Save")) { EditorPrefs.SetString(PrefKey, textValue); Debug.Log("Text value saved."); } if (GUILayout.Button("Load")) { textValue = EditorPrefs.GetString(PrefKey, string.Empty); Debug.Log("Text value loaded."); } } }
数値を保存、取得するための関数
int 型、float 型の保存、取得をするための関数として、SetInt、GetInt、SetFloat、GetFloat があります。
public static void SetInt (string key, int value); public static int GetInt (string key, int defaultValue= 0); public static void SetFloat (string key, float value); public static float GetFloat (string key, float defaultValue= 0.0F);
EditorPrefs.HasKey
Key が存在していたら true、存在していなければ false を返す関数です。
public static bool HasKey (string key);
EditorPrefs.DeleteKey
設定情報から key と対応する値を削除します。
public static void DeleteKey (string key);
EditorPrefs.DeleteAll
設定情報からすべてのキーと値を削除します。注意して使用してください。