I've been struggling with IMGUI (Legacy and Editor GUI system) a lot. Problem is I cannot get my head around this Instant way and all the different events.
I built a simple example to demonstrate one of the many frustration I'm having with this system.
bool toggleValue;
void OnGUI()
{
if (toggleValue = GUILayout.Toggle(toggleValue, "Toggle"))
{
EditorGUILayout.LabelField("This is a label");
}
}
Alright, so, in this very simple code, I have a native toggle that shows or not a label depending on it's state. This works perfectly.
Now, I'm writing a piece myself.
bool toggleValue;
void OnGUI()
{
if (toggleValue = Toggle(toggleValue, "Toggle"))
{
EditorGUILayout.LabelField("This is a label");
}
}
bool Toggle(bool state, string label)
{
GUILayout.Label(label, state ? EditorStyles.boldLabel : GUIStyle.none);
if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
return !state;
return state;
}
My goal with this one is to manually reproduce the behaviour of a toggle: My clickable label is bold when active and normal when disable. Similarly to the checkbox graphic of the native toggle. Then, if I catch a click on it's rect, I return the opposite of the state.
In my head, this is suppose to work. However, I'm aware that there's a lot going on with the OnGUI function like the events Repaint and Layout for which the layout needs to be consistent during a frame. Here the error is
ArgumentException: Getting control 1's position in a group with only 1 controls when doing MouseDown
but often also errors like this one
ArgumentException: GUILayout: Mismatched LayoutGroup.MouseDown
I know that these errors are when you change the content between Layout and Repaint. However I cannot find a fix for my simple control. So here is my question.
With the same arguments given to my function Toggle, what do I need to take care of so the toggle works?
I feel like if I have the answer to this, I might be able to understand the key to this system.
Thank you very much