I’m using GUILayout.SelectionGrid to draw buttons that can be controlled with the keyboard.
This works pretty fine. But I can’t figure out how to make them also controlable with the mouse correctly.
How can I select the button that is currently hovered?
Even though the hover effect of buttons works, the button that is hovered is not the one that is marked as “selected” in the SelectionGrid. How can this be achieved?
The current behaviour is as follows:
If button 1 is “selected” by the SelectionGrid initially and the mouse hovers over button 3 and clicks button 3, in fact button 1 is clicked. But right after that button 3 is marked as “selected” by the SelectionGrid. Clicking again on button 3 results in a click of button 3.
There isn’t anything built-in, so the only way I can think of is to compare Event.current.mousePosition to the rects of the items in the SelectionGrid, using Rect.Contains. Either that or you might be able to use GUI.tooltip as a sort of hack.
Comparing the mouse position sounds like a hack to me. I can’t use this approach if I use GUILayout, right? If GUI is used instead of GUILayout only the position for the first button is defined, as far as I can see (Unity - Scripting API: GUI.SelectionGrid). How can I calculate the position for the remaining buttons?
Is it possible to access the Rects of the selection grid for a specific item?
I already had a look at the GUI.tooltip, but didn’t figure out how to use it with the example in the documentation of GUI.SelectionGrid. This is how my implementation looks like.
I had a similar problem. Here is my hacky solution. I keep track of the frame in which the mouse was clicked, and its position. (Note that “selected”, “mouseUpPosition” and “mouseUpFrameCount” are all member variables of the script.) On click I then test whether the click was within the selection grid, using GUILayoutUtility.GetLastRect. In my case this is running within a GUI.Window, but it should work inside any OnGUI method. For some reason I had to use Input.GetMouseButtonUp, when it seems more correct to check if (Event.current.type == EventType,MouseUp).