- Home /
How can I get the last assigned ControlID?
Ideally, without using reflection, I would like a way to get the last ControlID assigned to a control. I'm dealing with a dynamic GUI with lots of TextFields and other complex controls, so I don't really want to rebuild every GUI control just so I can use GetControlID() and assign it to the controls myself via GUIStyle.Draw().
Apparently, assigning control name using GUI.SetNextControlName() and GUI.GetNameOfFocusedControl() do not function correctly with dynamic GUIs.
Is there any way to get the ControlID of the last control drawn? I'm looking for something like this:
value = EditorGUILayout.TextField(value, style, options);
int controlID = GUIUtility.GetLastControlID();
It seems like this may not possible, but perhaps I'm missing something in the API documentation.
How about using reflection?
Answer by numberkruncher · Oct 04, 2013 at 01:14 AM
Yes this would be a really useful function!
Here is a dirty trick which I have used in the past:
int nextControlID = GUIUtility.GetControlID(FocusType.Passive) + 1;
value = EditorGUILayout.TextField(value, style, options);
This may not always be 100% reliable, so be sure to test thoroughly!
Please vote for feature here:
http://feedback.unity3d.com/unity/all-categories/1/hot/active/4449--guiutilitygetlastcontrolid
Thanks! Actually, I already requested the feature here: http://feedback.unity3d.com/unity/all-categories/1/hot/active/guiutilitygetlastcontrolid
Hopefully they can add that to the API.
This IS dirty, but its the only thing I've found that actually works :/
Gonna go +1 you
Answer by Nevermind · Nov 27, 2013 at 11:55 AM
You can also cheat with a bit of reflection:
public static FieldInfo LastControlIdField=typeof(EditorGUI).GetField("lastControlID", BindingFlags.Static|BindingFlags.NonPublic);
public static int GetLastControlId(){
if(LastControlIdField==null){
Debug.LogError("Compatibility with Unity broke: can't find lastControlId field in EditorGUI");
return 0;
}
return (int)LastControlIdField.GetValue(null);
}
This only works in editor with EditorGUI.* calls, though: in-game GUI does not seem to store the last control ID anywhere.
the trick is great but need some update: typeof(EditorGUIUtility).GetField("s_LastControlID", BindingFlags.Static | BindingFlags.NonPublic);
, the variable is now in EditorGUIUtility
and name changed to s_LastControlID
.