Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ArnCarveris/86457a03819d7e31f891b17726122ef1 to your computer and use it in GitHub Desktop.
Save ArnCarveris/86457a03819d7e31f891b17726122ef1 to your computer and use it in GitHub Desktop.

I think using scopes greatly improves readability. Here's an example of converting a larger section of code. The indenting makes it immediately clear when a scopes begins and ends. Both snippets of code draw the exact same controls.

Before:

EditorGUILayout.BeginVertical("box");
disable = EditorGUILayout.Toggle("Disable Sliders", disable);
indent = EditorGUILayout.IntSlider("Indent Sliders", indent, 1, 4);

EditorGUI.indentLevel = indent;
EditorGUI.BeginDisabledGroup(disable);
EditorGUI.BeginChangeCheck();
width = EditorGUILayout.IntSlider("Width", width, 1, 10);
if (EditorGUI.EndChangeCheck())
	Debug.Log("Width was changed");
EditorGUI.BeginChangeCheck();
height = EditorGUILayout.IntSlider("Height", height, 1, 5);
if (EditorGUI.EndChangeCheck())
	Debug.Log("Height was changed");
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel = 0;
EditorGUILayout.EndVertical();

EditorGUILayout.LabelField("Table", EditorStyles.centeredGreyMiniLabel);

scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
EditorGUILayout.BeginHorizontal();
for (int x = 0; x < table.GetLength(0) && x < width; x++)
{
	EditorGUILayout.BeginVertical("box");
	for (int y = 0; y < table.GetLength(1) && y < height; y++)
		EditorGUILayout.LabelField(table[x, y], GUILayout.Width(25));
	EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();

After:

using (new EditorGUILayout.VerticalScope("box"))
{
	disable = EditorGUILayout.Toggle("Disable Sliders", disable);
	indent = EditorGUILayout.IntSlider("Indent Sliders", indent, 1, 4);

	using (new EditorGUI.IndentLevelScope(indent))
	{
		using (new EditorGUI.DisabledGroupScope(disable))
		{
			using (var check = new EditorGUI.ChangeCheckScope())
			{
				width = EditorGUILayout.IntSlider("Width", width, 1, 10);
				if (check.changed)
					Debug.Log("Width was changed");
			}
			using (var check = new EditorGUI.ChangeCheckScope())
			{
				height = EditorGUILayout.IntSlider("Height", height, 1, 5);
				if (check.changed)
					Debug.Log("Height was changed");
			}
		}
	}
}

EditorGUILayout.LabelField("Table", EditorStyles.centeredGreyMiniLabel);

using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPosition))
{
	using (new EditorGUILayout.HorizontalScope())
	{
		scrollPosition = scroll.scrollPosition;
		for (int x = 0; x < table.GetLength(0) && x < width; x++)
		{
			using (new EditorGUILayout.VerticalScope("box"))
			{
				for (int y = 0; y < table.GetLength(1) && y < height; y++)
				{
					EditorGUILayout.LabelField(table[x, y], GUILayout.Width(25));
				}
			}
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment