Created
October 7, 2023 20:11
-
-
Save AmbientLion/4fc694727bd3c0b4712d011a454cdf00 to your computer and use it in GitHub Desktop.
Prevent Focus Loss in Unity OnSceneGUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is an Editor class for some Component class | |
*/ | |
[CustomEditor(typeof(SomeComponent))] | |
public class SomeComponentEditor : Editor { | |
// OnSceneGUI() is often used to paint or interact with objects in the Scene | |
// at edit time. Here we show how to prevent clicking on a game scene from | |
// resulting in a change of focused/selected element in the Scene hierarchy. | |
private void OnSceneGUI() { | |
if (Event.current.type == EventType.MouseDown) { | |
// get the controlID of the passively focused item (typically the selected Gameobject) | |
int controlId = GUIUtility.GetControlID(FocusType.Passive); | |
// YOUR LOGIC HERE: | |
// perform you processing here... | |
// force focus (hot control) back to the original object, even if the click event would shift it | |
GUIUtility.hotControl = controlId; // force focus on the current control | |
Event.current.Use(); // consume the event so it doesn't get passed on to other handlers | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a technique that can be used when writing Unity component editor classes.
Editors are used to control how the behavior of game objects (or their components) works in the Editor window.
Occasionally, we want to create editors that response to things like mouse events (up, down, move etc) but swallow these events after processing them. Essentially, we don't want the selected object in the scene view to change while (or after) we do things like paint on terrain, place objects in the scene, etc.
The GUIUtility class provides methods like
GetControlID()
and.hotControl
which are normally used when creating your own UI controls. However, we can use them in such cases to control which scene elements retain focus after mouse interaction.