Skip to content

Instantly share code, notes, and snippets.

@quasiblob
Created January 14, 2021 08:41
Show Gist options
  • Save quasiblob/8f77b40015a39db964ebbd81bd1eeeb7 to your computer and use it in GitHub Desktop.
Save quasiblob/8f77b40015a39db964ebbd81bd1eeeb7 to your computer and use it in GitHub Desktop.
How to prevent Unity Editor Scene default selection behavior
using UnityEngine;
using UnityEditor;
namespace ConditionalEditorSelection
{
// 2021.1.1
// Written by Sami S.
// How to prevent Unity Editor Scene default selection behavior
// NOTE:
// Open EditorSelection from menu "Window"
// Enter a filter matching scene object name
// Click any object, only objects matching filter get selected
// Clicking empty areas will deselect current selection
public class EditorSelection : EditorWindow
{
GameObject selection;
GameObject previousSelection;
string nameFilter = "filter here";
[MenuItem("Window/ConditionalSelection")]
static void Init()
{
EditorSelection window = (EditorSelection)EditorWindow.GetWindow(typeof(EditorSelection));
window.Show();
}
void OnEnable()
{
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
SceneView.onSceneGUIDelegate += this.OnSceneGUI;
}
void OnGUI()
{
GUILayout.Label("Selection filter:", EditorStyles.boldLabel);
nameFilter = EditorGUILayout.TextField(nameFilter);
}
void OnSelectionChange()
{
Debug.Log("OnSelectionChange");
}
void OnSceneGUI(SceneView sceneView)
{
// Skip layouting
HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
if (Event.current.type == EventType.Layout)
{
return;
}
if (Event.current.type == EventType.MouseMove)
{
var go = HandleUtility.PickGameObject(Event.current.mousePosition, false);
selection = go;
}
if (Event.current.type == EventType.MouseDown)
{
// Debug.Log("id: " + GUIUtility.hotControl);
if (selection != null)
{
previousSelection = selection;
Debug.Log("selection:" + selection.name);
}
}
// conditional selection
if (Event.current.type == EventType.MouseUp)
{
if (selection != null && selection.name.ToLower().Contains(nameFilter))
{
Selection.objects = new GameObject[1] { selection };
}
if (selection == null)
{
Selection.objects = new GameObject[0];
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment