Unityではエディタを拡張することができ、独自のウインドウを作成することができます。
基本的な流れ
UnityEditorを追加
using UnityEditor;
メニューに追加
[MenuItem("Window/Sample/HelloWorld")]
ウインドウを生成
EditorWindow.GetWindow<HelloWorldWindow>("TITLE")
GUIを記述
EditorWindowを拡張したクラスのOnGUIにUIを記述します。
public class HelloWorldWindow : EditorWindow{
void OnGUI(){
...
}
}
主なGUI
ラベル
EditorGUILayout.LabelField("ラベル");
テキスト入力
_data.name = EditorGUILayout.TextField(_data.name);
アセット入力
ドラッグ&ドロップやファイルの選択ができます。
objTypeはAssetの型、例えば、TextAsset、Texture2D、DefaultAsset(フォルダなど)があります。
_data.textAsset = EditorGUILayout.ObjectField(_data.textAsset, typeof(TextAsset), false) as TextAsset;
ボタン
if(GUILayout.Button("OK")){
//OK
}
処理を実行
OK押下後に何らかの処理を実行します。
サンプル
名前をつけて指定したデータを保存します。 UnityEditor向けのスクリプトはEditorフォルダ内に配置する必要があります。
using UnityEngine;
using UnityEditor;
using System.IO;
public class HelloWorld{
[MenuItem("Window/Sample/HelloWorld")]
public static void Main(){
EditorWindow.GetWindow<HelloWorldWindow>("File Copy");
}
}
public class HelloWorldData{
public string name;
public TextAsset textAsset;
}
public class FileCopy{
public void Execute(HelloWorldData data){
if(string.IsNullOrEmpty(data.name)){
Debug.LogWarning("empty name");
return;
}
if(null == data.textAsset){
Debug.LogWarning("null TextAsset");
return;
}
//パス取得
var textAssetPath = AssetDatabase.GetAssetPath(data.textAsset);
if(!File.Exists(textAssetPath)){
Debug.LogWarning("file not exists : " + textAssetPath);
return;
}
//ファイル情報
var textAssetFileInfo = new FileInfo(textAssetPath);
var directoryInfo = textAssetFileInfo.Directory;
//保存
var outputPath = directoryInfo.FullName + "/" + data.name + textAssetFileInfo.Extension;
var sw = new StreamWriter(outputPath, false, System.Text.Encoding.UTF8);
sw.Write(data.textAsset.text);
sw.Close();
Debug.Log("* save");
AssetDatabase.Refresh();
}
}
public class HelloWorldWindow : EditorWindow{
protected HelloWorldData _data = new HelloWorldData();
void OnGUI(){
//テキスト
EditorGUILayout.LabelField("保存するファイル名");
_data.name = EditorGUILayout.TextField(_data.name);
//アセット
EditorGUILayout.LabelField("コピーするデータ");
_data.textAsset = EditorGUILayout.ObjectField(_data.textAsset, typeof(TextAsset), false) as TextAsset;
//ボタン
if(GUILayout.Button("OK")){
new FileCopy().Execute(_data);
}
}
}