Skip to content

Instantly share code, notes, and snippets.

@kurokuru
Last active May 13, 2019 14:05
Show Gist options
  • Save kurokuru/1fab99dc08e8ba91b98cb45de19a828b to your computer and use it in GitHub Desktop.
Save kurokuru/1fab99dc08e8ba91b98cb45de19a828b to your computer and use it in GitHub Desktop.
Unity Editor ScriptableObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// セーブするセッティングデータ
/// </summary>
public class ExampleEditorSetting : ScriptableObject
{
public string Text;
public bool Toggle;
}
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Editorスクリプト
/// </summary>
public class ExampleEditorWindow : EditorWindow
{
// 設定用のScriptableObject
public static ExampleEditorSetting setting;
[MenuItem("Tools/ExampleEditorWindow")]
public static void Open()
{
GetWindow<ExampleEditorWindow>();
// 設定を保存(読み込み)するパス ScriptableObjectは.assetを付けないと正しく読んでくれません
var path = "Assets/Editor/ExampleEditorSetting.asset";
setting = AssetDatabase.LoadAssetAtPath<ExampleEditorSetting>(path);
if(setting==null)
{ // ロードしてnullだったら存在しないので生成
setting = ScriptableObject.CreateInstance<ExampleEditorSetting>(); // ScriptableObjectはnewではなくCreateInstanceを使います
AssetDatabase.CreateAsset(setting, path);
}
}
private void OnGUI()
{
GUILayout.Label("Text:");
// ここから変更を検知
EditorGUI.BeginChangeCheck();
// とりあえず入力値を仮の変数に入れる
var text = GUILayout.TextArea(setting.Text);
var toggle = GUILayout.Toggle(setting.Toggle, "Toggle");
if (EditorGUI.EndChangeCheck())
{ // 変更を検知した場合、設定ファイルに戻す
UnityEditor.Undo.RecordObject(setting, "Edit ExampleEditorWindow"); // こうするとRedo/Undoが簡単に実装
setting.Text = text;
setting.Toggle = toggle;
EditorUtility.SetDirty(setting); // Dirtyフラグを立てることで、Unity終了時に勝手に.assetに書き出す
}
}
private void Update()
{
Repaint(); // Undo.RecordObjectを使うときは入れたほうが更新描画が正しく動く
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment