Skip to content

Instantly share code, notes, and snippets.

@yuri-tikhomirov
Last active July 8, 2016 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuri-tikhomirov/dd09c244cb75041f180640fc71722078 to your computer and use it in GitHub Desktop.
Save yuri-tikhomirov/dd09c244cb75041f180640fc71722078 to your computer and use it in GitHub Desktop.
A Layout tool for Unity3D for scoped OnGUI() programming with no garbage production.
using System;
using UnityEngine;
using System.Collections.Generic;
//
// GUI layout tools (c) Yuri Tikhomirov at Cerevrum Inc.
//
// A useless* tool not to produce more garbage when using with Unity3D IMGUI.
//
// * - cause anyway IMGUI produces garbage inside
//
//
// Usage:
//
// class MB : MonoBehaviour {
// GUILayTools layout = new GUILayTools();
// void OnGUI() {
// using (layout.VerticalScope()) {
// using (layout.ScrollViewScope(ref scrollPos)) {
// ...
// }
// }
// }
//
public class GUILayTools : IDisposable
{
enum ScopeType
{
Area,
Vertical,
Horizontal,
Scrollview,
}
private Stack<ScopeType> stack = new Stack<ScopeType>(32);
public IDisposable AreaScope(Rect rect)
{
GUILayout.BeginArea(rect);
stack.Push(ScopeType.Area);
return this;
}
public IDisposable VerticalScope()
{
GUILayout.BeginVertical();
stack.Push(ScopeType.Vertical);
return this;
}
public IDisposable HorizontalScope()
{
GUILayout.BeginHorizontal();
stack.Push(ScopeType.Vertical);
return this;
}
public IDisposable ScrollViewScope(ref Vector2 scrollPosition)
{
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
stack.Push(ScopeType.Scrollview);
return this;
}
#region IDisposable implementation
public void Dispose ()
{
var scope = stack.Pop();
switch (scope)
{
case ScopeType.Area:
GUILayout.EndArea();
break;
case ScopeType.Vertical:
GUILayout.EndVertical();
break;
case ScopeType.Horizontal:
GUILayout.EndHorizontal();
break;
case ScopeType.Scrollview:
GUILayout.EndScrollView();
break;
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment