Unity Custom Editor: Context Menu in a Scene View

Hi. I have started new series of tutorials describing step by step building Adventure Game Engine on a top of a Unity.

Today i will show You something simple but not very obvious. I wanted to make context menu with custom actions in editor to simplify scene building . I want to tailor the unity engine for this narrow type of games. I next tutorial i want to make editor for player’s walk path. This path will be represented by graph with assigned animations and path finding algorithm.

It is good practice to place custom editor in “Editor” folder. Thanks to that this script wil be excluded from final build. “Editor” folders can be placed in any branch of “Assets”

This code bellow adds custom action “Do something” to any scene object selected by shift+ right mouse click. This action only prints debug.

That is the code:

using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

/*
 
	This code is based on more advanced example found here:

   // https://forum.unity.com/threads/sceneview-context-menu-script-free.525029/
   
	I have simplified this code for tutorial purpose
*/

#if UNITY_EDITOR
[InitializeOnLoad]
public class SceneViewContextMenuInitializer : Editor
{


	// Key that's got to be pressed when right clicking, to get a context menu.
	static readonly EventModifiers modifier = EventModifiers.Shift;


	static SceneViewContextMenuInitializer()
	{
        SceneView.onSceneGUIDelegate -= OnSceneGUI;
        SceneView.onSceneGUIDelegate += OnSceneGUI;
    }



    static void OnSceneGUI(SceneView sceneview)
	{
		// If shift + right mouse click.
        if (Event.current.modifiers == modifier && Event.current.button == 1 && Event.current.type == EventType.MouseDown)
		{
			

			// Ray from editor camera.
			var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

			// Check if object selected.
			var materialIndex = 0;
			var go = HandleUtility.PickGameObject(Event.current.mousePosition, out materialIndex);

			// Show menu.
			if (go != null)
			{
				ShowMenu(go, ray);
				return;
			}
			
			
		}
    }

	

	// Menu from context items.
	static void ShowMenu(GameObject go, Ray ray)
	{
		var menu = new GenericMenu();
		

		menu.AddItem(new GUIContent("Do something"), false, () => menuAction()); 
		// Show as context.
		menu.ShowAsContext();
	}
	private static void menuAction () {
		Debug.Log("worked");
	}


}
#endif

Class must inherit on Editor class and implement on onSceneGui method. When shift and right mouse click event is produced the object is picked from the scene with ray cast from scene camera. Then context menu is displayed.

Comments are closed.