Last active
July 8, 2016 21:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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