- Home /
How do you prevent GUI.DragWindow from letting the window go offscreen?
GUI.DragWindow will happily let me drag my entire window offscreen (and leave it there). I'm guessing I could check the current window rect and make sure it's not going offscreen, but wouldn't that mean checking it on the next frame? Seems like it would get jittery. I'm assuming I can check for mouse in bounds of screen and not call drag, might help a little. What's the best way to do this?
Stopping your mouse from going too near the edge sounds like a clever workaround. There might be a real solution though. :)
Yeah, I'm actually getting close to it already. I'll leave this open because it might help someone else.
Answer by Bunny83 · Apr 02, 2011 at 01:25 AM
GUI.Window or GUILayout.Window returns the changed Rect. If you wouldn't assign it back to your windowrect variable the window wouldn't even move 1 pixel. The movement happens next frame when you call Window again with the new coordinates. So limiting the returned Rect to your desired area should be enough.
// C#
Rect windowRect = new Rect(10,10,100,100);
void OnGUI() { windowRect = GUI.Window(0,windowRect,MyWindowFunc,"Title"); windowRect.x = Mathf.Clamp(windowRect.x,0,Screen.width-windowRect.width); windowRect.y = Mathf.Clamp(windowRect.y,0,Screen.height-windowRect.height); }
edit
I think that would be a nice job for a seperate function ;) ClampToScreen()
Rect ClampToScreen(Rect r) { r.x = Mathf.Clamp(r.x,0,Screen.width-r.width); r.y = Mathf.Clamp(r.y,0,Screen.height-r.height); return r; }
void OnGUI() { windowRect = ClampToScreen(GUI.Window(0,windowRect,MyWindowFunc,"Title")); }
That's where I was heading, but forgot about Clamp which cleans things up. I haven't tried your code yet, but looks good.
i was fighting with a similar problem for 3 hours!! thanks a lot!! very useful!!
This works a treat, I had been trying to come up with a way of doing this myself but hit a dead end. I would throw you a +1 but I'm not allowed :(
Answer by PaoloAbela · Jun 04, 2020 at 03:37 PM
To build on top of @Bunny83's answer, this works perfectly in Unity 2019.3 and gives you the exact size of the window:
static Rect ClampRectToSceneView(Rect rect)
{
const int SceneViewTopBarHeight = 15;
const int DistanceFromBorders = 10; //you can remove this if you want
Rect sceneViewArea = SceneView.lastActiveSceneView.position;
rect.x = Mathf.Clamp(rect.x, DistanceFromBorders, sceneViewArea.width - rect.width - DistanceFromBorders);
rect.y = Mathf.Clamp(rect.y, DistanceFromBorders + SceneViewTopBarHeight, sceneViewArea.height - rect.height - DistanceFromBorders);
return rect;
}