強火で進め

このブログではプログラム関連の記事を中心に書いてます。

メニューに独自機能を追加する方法

Unityのエディタ拡張についての話。メニューに独自機能を追加する方法。

ファイルは Editor というフォルダを作り、その下に配置する必要が有ります。

プログラムは JavaScript の場合はこの様な記述に成ります。今回のサンプルプログラムは選択したオブジェクト(GameObject)のPositionの値を0にリセットします。
【Test.js】

@MenuItem ("Custom/Reset Position")
static function ResetPosition () {
	for (var gameObj in Selection.gameObjects) {
		print ("Selection GameObjet : "+gameObj.name);
		gameObj.transform.position = Vector3(0, 0, 0);
	}
}

@MenuItem でメニューのどの位置に追加するかを指定します。

今回は Custom というメニューを追加し、その下の Reset Position を指定しました。

@MenuItem ("Custom/Reset Position")

この様に新たにメニューが追加されます。

Unity Script Reference – MenuItem
http://unity3d.com/support/documentation/ScriptReference/MenuItem.html

同様に編集用のWindowを表示する EditorWindow というものも有るのですがこちらはサンプルをそのまま試してみても GetWindow() でデータ取得に失敗して上手く動きませんでした。

var window : MyWindow = EditorWindow.GetWindow (MyWindow);

この様なエラー文が出ます。

Instance of MyWindow couldn't be created because there is no script with that name.
UnityEditor.EditorWindow:GetWindow(Type)
MyWindow:Init() (at Assets/Editor/NewBehaviourScript.cs:14)
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.EditorWindow.GetWindow (System.Type t, Boolean utility, System.String title, Boolean focus)
UnityEditor.EditorWindow.GetWindow (System.Type t)
MyWindow.Init () (at Assets/Editor/NewBehaviourScript.cs:14)

こちら使い方についてご存知の方はコメント欄で教えて貰えると嬉しいです。ちなみにUnityのバージョンは 3.3.0f3 です。
(追記)解決しました。解決方法はこちら

Unity Script Reference – EditorWindow
http://unity3d.com/support/documentation/ScriptReference/EditorWindow.html