- Home /
How expensive is Rect.Contains(Event.current.mousePosition)?
Also, how expensive is it to use the style options such as OnHover? Are they constantly called even if the GUI is incapable of receiving it? Are they checked even when no Mouse Input is received on the specific GUI?(I.E. A label with OnNormal/OnHover shouldn't change)
The reason behind me asking is simply because I want to run roughly 100+ pieces of GUI and I'm trying to figure out the best way to optimize.
Thanks for any info!
Answer by numberkruncher · Sep 24, 2013 at 12:55 AM
Rect.Contains(Event.current.mousePosition)
is relatively efficient though you should avoid evaluating this for non-mouse events.
Also, how expensive is it to use the style options such as OnHover? Are they constantly called even if the GUI is incapable of receiving it? Are they checked even when no Mouse Input is received on the specific GUI?(I.E. A label with OnNormal/OnHover shouldn't change)
I wouldn't think there was very much difference since these states are determined when your GUI is being repainted. When a style is drawn with the control ID Unity will determine the current state based upon internal state (like GUIUtility.hotControl
). Otherwise you can specify the style of GUI to go with.
void OnGUI() {
Event e = Event.current;
int yourControlID = GUIUtility.GetControlID(FocusType.Passive);
Rect yourRect = YourControlRect;
GUIStyle style = YourControlStyle;
switch (e.GetTypeForControl(yourControlID)) {
case EventType.MouseDown:
if (yourRect.Contains(e.mousePosition)) {
// Lock on to your custom button control.
GUIUtility.hotControl = yourControlID;
e.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == yourControlID) {
// Release lock - Important!
GUIUtility.hotControl = 0;
e.Use();
if (yourRect.Contains(e.mousePosition)) {
// Do something!
// Your custom button was clicked!
}
}
break;
case EventType.Repaint:
// The following will determine whether to use "OnHover" style
// upon repainting GUI.
style.Draw(yourRect, GUIContent.none, yourControlID);
// OR! - Specify state manually!
style.Draw(yourRect, GUIContent.none, false, false, false, false);
break;
}
}
The reason behind me asking is simply because I want to run roughly 100+ pieces of GUI and I'm trying to figure out the best way to optimize.
The standard Unity GUI functionality is not very efficient and for large GUI's it is generally better to use a solution like NGUI. In fact, I believe that a revamped version of NGUI will be built into a future version of Unity with the new name uGUI (see Unite'13 video on YouTube for further information!).
Very good explanation-- Thanks! Covered all of the bases.