I have an EditorWindow for my behaviour tree implementation that draws Window objects for each node. I need to know which node was selected/clicked last so I can create the necessary controls for the details of that control. I’ve seen that you can store the ID in your DoWindow method, but this doesn’t seem to always be the last window drawn - which is a shame.
Not sure if this is related but I manage all windows in a WindowManager class. Whenever a script instantiates a window it first registers that Window’s rect with the WindowManager and the manager sends back the unique ID to use when creating the actual Window.
After that I do a check every few Update()s to see if the mouse cursor is inside any of the Window rects. WindowManager also does a test for leftmouseclick(), if detected and the mouse is over a window, it logs the ID of that window as lastClicked.
It’s a touch overkill and probably not efficient but my use case was limited to 1 <= N <= 10 windows so the cursor-in-window test was quick.
It seems that in the editor, the Event.current property only returns Repaint and Layout for me. However the black magic suggested by PaulAsh does work and I’ve refactored this below:
static System.Reflection.FieldInfo s_focusedWindow = null;
static public int FocusedWindow
{
get
{
if(s_focusedWindow == null)
{
s_focusedWindow = typeof(GUI).GetField("focusedWindow",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
}
return (int) s_focusedWindow.GetValue(null);
}
}
It returns -1 if there’s no focus and the window ID for the item with focus if one has been clicked. It also reverts to -1 if you click away from a window.
I’m using this in the editor and I have to say I don’t much like it, but… it does work and work well. However, I have to wonder why on earth it is not public API - it’s such a useful property!
I also looked at Input.GetMouseButtonUp() but wasn’t terribly surprised to see this not work either.
If anyone else has a more acceptable solution, then please post it and I’ll accept that as the answer instead, but in the short term it works so well and I don’t have another two hours to spend googling the subject.