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?

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

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.