Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Neatou · Nov 24, 2021 at 02:35 AM · editorinputreflectiononguievent-handling

How to make OnGUI TextField in gameView accept keyboard input during edit mode?

I've been learning about reflection lately and got the idea to build a runtime GUI inspector. Everything works properly in play mode, but then I discovered I could add the [ExecuteInEditMode] attribute to preview the GUI during edit mode.


THEN I discovered I can add this little blurb to OnGUI

 // makes mouse work in gameview edit mode!
 // https://answers.unity.com/questions/1679704/is-there-a-way-to-implement-mouse-events-in-the-ga.html
 if (Event.current.type == EventType.Layout || Event.current.type == EventType.Repaint)
 {
     UnityEditor.EditorUtility.SetDirty(this);
 }

which works surprisingly well to capture mouse input in edit mode, so I can interact with toggles, sliders, buttons, draggable windows, etc, in the game view while still in edit mode. This is a totally unnecessary feature, but honestly it blows my freaking mind.


The only edit-mode feature it seems to lack is keyboard input. GUI text field controls will display the mouse caret when clicked, but keyboard input seems to be eaten by the editor for hotkeys or whatever.


I can reach keyboard input through this workaround

 // https://github.com/pjc0247/UnityHack
 [InitializeOnLoadMethod]
 static void EditorInit()
 {
     FieldInfo info = typeof(EditorApplication).GetField("globalEventHandler", BindingFlags.Static | BindingFlags.NonPublic);
     EditorApplication.CallbackFunction value = (EditorApplication.CallbackFunction)info.GetValue(null);
     value += EditorKeyPress;
     info.SetValue(null, value);
 }
 static void EditorKeyPress()
 {
     var key = Event.current.keyCode;
     if (key != KeyCode.None)
     {
         Debug.Log($"Global key event: {key}");
 
         // TODO: reroute event to gameView?
 
         // ???
         //var view = EditorWindow.GetWindow(System.Type.GetType("UnityEditor.GameView,UnityEditor"));
         //view.SetDirty();
         //view.SendEvent(Event.current);
         //view.SendEvent(Event.KeyboardEvent(key.ToString()));
         //Event.current.Use(); // block event ???
         //GUIDrawer.PressKey(key);
     }
 }

but all my attempts to reroute the event have failed.


Hopefully someone has a solution?

Rest of the code:

 [ExecuteInEditMode]
 public class GUIDrawer : MonoBehaviour
 {
     // https://docs.unity3d.com/ScriptReference/GUI.Window.html
 
     public Rect windowRect = new Rect(0, 0, 600, 1000);
     public Object obj; // object to create an inspector for
 
     private float prefixWidth = 100;
     private FieldInfo[] fields;
     private bool reflected;
 
     private void OnEnable()
     {
         reflected = false;
         Reflect();
     }
 
     void OnGUI()
     {
 #if UNITY_EDITOR
         // makes mouse work in gameview edit mode!
         // https://answers.unity.com/questions/1679704/is-there-a-way-to-implement-mouse-events-in-the-ga.html
         if (Event.current.type == EventType.Layout || Event.current.type == EventType.Repaint)
         {
             UnityEditor.EditorUtility.SetDirty(this);
         }
         else if (Event.current.isKey)
         {
             // never called
             Debug.Log($"Key event: {Event.current.keyCode}");
         }
         else if (Event.current.isMouse)
         {
             // called only when clicking outside gui window in gameview
             Debug.Log($"Mouse event: {Event.current}");
         }
         else
         {
             // mouse events show up here with the output:
             // Unhandled event: Used
             Debug.Log($"Unhandled event: {Event.current}");
         }
 #endif
 
         if (obj != null)
         {
             // Register the window. Notice the 3rd parameter
             windowRect = GUI.Window(0, windowRect, DrawWindow, "Cool Window");
         }
     }
     private void Reflect(bool reflected = false)
     {
         if (!reflected)
         {
             // guess which fields get serialized without Editor?
             var type = obj.GetType();
             fields = type.GetFields();
 
             this.reflected = true;
 
             // TODO: BindingFlags, attributes, properties, methods
             // var bindingFlags = BindingFlags.Public | ...;
             // var methods = type.GetMethods
             // var props = type.GetProperties
             // var attributes = type.GetCustomAttributes
         }
     }
     private void DrawWindow(int windowID)
     {
         // finding fields to draw
         if (!reflected)
             Reflect();
 
         // draw fields based on type
         foreach (var field in fields)
             DrawField(field);
 
         // top-bar drag handle
         Rect dragArea = new Rect(0, 0, windowRect.width, 15);
         GUI.DragWindow(dragArea);
     }
     private void DrawField(FieldInfo x)
     {
         // WORK IN PROGRESS
 
         GUILayout.BeginHorizontal();
         System.Type _type = x.FieldType;
         object value = x.GetValue(obj);
         GUILayout.Label(x.Name, GUILayout.Width(prefixWidth));
 
         if (value is string)
         {
             x.SetValue(obj, GUILayout.TextField(value.ToString()));
             //if (GUI.GetNameOfFocusedControl() != "str_input0")
             //GUI.SetNextControlName($"str_input{count++}");
             //GUI.FocusControl("str_input0");
         }
         else if (value is bool)
         {
             x.SetValue(obj, GUILayout.Toggle((bool)value, ""));
         }
         else if (value is float)
         {
             var range = x.GetCustomAttribute<RangeAttribute>();
             if (range != null)
             {
                 x.SetValue(obj, GUILayout.HorizontalSlider((float)value, range.min, range.max));
             }
             else
             {
                 var input = GUILayout.TextField(value.ToString());
                 if (float.TryParse(input, out float result))
                 {
                     x.SetValue(obj, result);
                 }
             }
         }
         else if (value is int)
         {
             var range = x.GetCustomAttribute<RangeAttribute>();
             if (range != null)
             {
                 float f = (int)value;
                 float input = GUILayout.HorizontalSlider(f, range.min, range.max);
                 x.SetValue(obj, Mathf.RoundToInt(input));
             }
             else
             {
                 var input = GUILayout.TextField(value.ToString());
                 if (int.TryParse(input, out int result))
                 {
                     x.SetValue(obj, result);
                 }
             }
         }
         else
         {
             GUILayout.Label($"{value}");
         }
 
         GUILayout.EndHorizontal();
     }

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

171 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

reflection propertyinfo.getvalue compiles fine but gives erros in editor 1 Answer

How to force Unity to Repaint an EditorWindow? 1 Answer

How to detect if project is Using new or Old Input System via code? 1 Answer

[Unity Editor] Emulate Touch Input - Still Asking 12/10 1 Answer

Shader Errors Strumpy Shader Editor 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges