青空の月

PHP, Unity, C#, アプリ開発関連について。

右クリックで表示されるコンテキストメニューを作る

 

昨日はコンポネント名の行を右クリックでのコンテキストメニュー追加してみたけど、

今度は自分で作ったEditorWindow内のコンテキストメニューを自作してみる。

 

こんな感じで追加される。

f:id:masa795:20130314135334p:plain

 

GenericMenu」を使うと拡張できる。

 ソースはこんな感じ。

using UnityEngine;
using UnityEditor;


public class MyWindow : EditorWindow {
    
	// Add menu item to the Window menu
	[MenuItem ("Window/My Window")]
	static void Init () {
		// Get existing open window or if none, make a new one:
		EditorWindow.GetWindow (false, "My Window");
	}
	
	// Implement your own editor GUI here.
	void OnGUI () {
		Event evt = Event.current;
		//ウインドウ内どこをクリックしてもコンテキストメニューを表示
		Rect contextRect = new Rect(0, 0, Screen.width, Screen.height);

		if (evt.type == EventType.ContextClick)
		{
			Vector2 mousePos = evt.mousePosition;
			if (contextRect.Contains(mousePos))
			{
				// Now create the menu, add items and show it
				GenericMenu menu = new GenericMenu();

				menu.AddItem(new GUIContent("MenuItem1"), false, Callback, "item 1");
				menu.AddItem(new GUIContent("MenuItem2"), false, Callback, "item 2");
				menu.AddSeparator("");
				menu.AddItem(new GUIContent("SubMenu/MenuItem3"), false, Callback, "item 3");

				menu.ShowAsContext();

				evt.Use();
			}
		}
	}

	void Callback(object obj)
	{
		Debug.Log("Selected: " + obj);
	}
}

 

今回はEditorWindowに追加したけど、CustomEditorのOnInspectorGUIでも使えるのでInspectorの拡張にも役立ちそう。

 

 

参考

http://docs.unity3d.com/Documentation/ScriptReference/GenericMenu.html