[Unity] A Debug UI That Leaves the Scene Clean and Draws in a Single DrawCall
This is the day 1 article of the KAYAC Unity Advent Calendar 2018.

I'm Hirayama, now in my third year at the company, and in this article I'll talk about a debug UI like the one above. This is a screenshot of a debug build of our Tokyo Prison .
The library that implements this feature is published on GitHub. It's used in an actual product, so I suppose you could use it as is, but since I built it with an "it's only for debugging" attitude, everything about it is rough around the edges. Please treat it strictly as a sample.
Note, 2019/06/18: the master branch is no longer compatible with this article. I've changed the links in the article to point to a branch from before the breaking changes. For the improvements I made afterwards, please see this article.
Motivation
You often want debug features on the actual device: an invincibility button, a display of enemy states you normally can't see, a button that simulates being disconnected, a display of the sound state, a stage select that doesn't normally exist; the list is endless. When making things like this in Unity, what's the best tool for the job?
UnityEngine.UI
For UI, debug or not, the first thing to consider is UnityEngine.UI. Put a button in the scene and it works right away.

This one.
You could argue this is fine, but since you're putting things in the scene, if you do it the normal way they end up in the product too. You could just disable them, but some people will worry they might somehow get enabled. With a scene, you can't use something like
#if IS_DEBUG
to strip them at compile time, so unless you build some more tedious, elaborate mechanism, you can't remove them from the product.
Also, when several people edit a scene, merging tends to get hard. It's fine if each scene has exactly one owner and nobody else touches it, but some teams can't work that way. In that case you don't want to touch scenes just for a debug feature. So the question becomes: can't we somehow do it with code alone?
UnityEngine.GUI
Of course, Unity also has a way to do it in code.

This one.
void OnGUI()
{
GUI.Button(new Rect(10, 10, 100, 50), "ボタン");
}
This puts up a button, and you can wrap it in something like IS_DEBUG to strip it from the product. But it has no fewer than three flaws I find unbearable.
- Its performance is terrible
- You have to write it in OnGUI
- It doesn't scale to the device's resolution
First, performance: it does GC Alloc every frame. Given its interface, that seems unavoidable, doesn't it? If you call a function called Button every frame and pass it a string like "ボタン" every frame, naturally objects get created every frame.
On top of that, each button adds two DrawCalls. That's a bit much, isn't it? On some devices one DrawCall takes about 0.1ms, so putting ten buttons in your debug features could make things 1ms slower.
Some people may take the view that "speed doesn't matter in a debug build", but I'm the opposite: I believe "debug builds and release builds should be as close in speed as possible". Otherwise, the debug build loses its value.
If it comes down to "you need a release build to check performance anyway", you need release builds that much more often, which is a pain. And when something goes wrong in a release build, you can't debug it. This was before Unity, but I've seen a case where the debug build was so slow the game was unplayable, so everyone used release builds day to day, and as a result nobody noticed the bugs at all. Partly because of experiences like that, I think even debug features should be fast enough. I'd like zero GC Alloc outside initialization, and at most a few DrawCalls no matter how many buttons there are.
Next, "you have to write it in OnGUI": I can't help thinking "why can't I just write it in Update?" Not being able to write it alongside the rest of the processing is inconvenient.
And worst of all is resolution. Positions and sizes are specified in physical pixels, so the size changes on devices with a different resolution. Filling the screen at 960x540 but only the top-left quarter at 1920x1080 is not something I can accept, all the more so on smartphones. You'd be in trouble if things got so small you couldn't press the buttons. It's unusable unless you can specify things in a virtual resolution and have them scaled appropriately.
And so I ended up making my own.
What I wanted to achieve by making my own
Here's what I wanted it to do.
- Do it with code alone (remove it from the product with #if IS_DEBUG or similar)
- Don't create gameObjects
- If possible, do it in one DrawCall
- Keep GC Alloc to a minimum
- Pass callbacks to buttons and sliders
- Create instances up front, rather than recreating them every frame
- Have windows, gauges, sliders, toggles, radio buttons, log windows and tables
- Be able to drag windows and minimize them
- Scale appropriately
In the end I made something that meets almost all of these. The screen I showed at the start is a single DrawCall, with no gameObjects.
How to make a window
Let's walk through putting up a debug UI with this library. As an example, I'll make a screen like this.

Code like the following generates it.
public class SampleWindow : DebugUiWindow
{
DebugUiLogWindow _log;
public SampleWindow(DebugUiManager manager) : base(manager, "SampleWindow")
{
var button = new DebugUiButton("ボタン", 100f);
button.onClick = () => { _log.Add("ボタンが押された!"); };
AddChildAuto(button);
var toggleGroup = new DebugUiToggleGroup(); // needed if you group them
var toggles = new DebugUiToggle[2];
toggles[0] = new DebugUiToggle("トグルA", 100f, 50f, toggleGroup);
toggles[0].onChangeToOn = () => { _log.Add("Aが有効になった"); };
AddChildAuto(toggles[0]);
toggles[1] = new DebugUiToggle("トグルB", 100f, 50f, toggleGroup);
toggles[1].onChangeToOn = () => { _log.Add("Bが有効になった"); };
AddChildAuto(toggles[1]);
var text = new DebugUiText("テキスト", fontSize: 20f, width: 80f, height: 20f);
AddChildAuto(text);
BreakLine();
_log = new DebugUiLogWindow(fontSize: 20f, lineHeight: 22f, lineCount: 10, width: 800f);
AddChildAuto(_log);
BreakLine();
var frameTimeGauge = new FrameTimeGauge(200f, 30f, null);
AddChildAuto(frameTimeGauge);
var slider = new DebugUiSlider("スライダー", -100f, 100f, 400f);
slider.onDragEnd = () => { _log.Add("スライダーが" + slider.value + "に変更された"); };
AddChildAuto(slider);
BreakLine();
var table = new DebugUiTable(
16f,
new List<float>(){ 80f, 80f, 120f },
3,
20f);
table.cells[0, 0] = "列A";
// (omitted)
table.cells[2, 2] = "データ23";
AddChildAuto(table);
AdjustSize();
}
}
The library provides a class called DebugUiWindow, and you write a class derived from it. You new up various controls (UI parts such as buttons and text) that inherit DebugUiControl and add them to the window with AddChildAuto(). BreakLine() starts a new line. Finally, calling AdjustSize() sizes the window automatically.
Buttons, toggles and sliders can be given callbacks for when their state changes; in the example above, those are onClick, onChangeToOn and onDragEnd.
Instances are created at initialization and used from then on, but if all you're doing is setting callbacks, you don't need to keep references to the instances you created. Most of the time you can get by without adding fields, as above.
Preparing the scene side
Next, the scene side. Under the canvas, set up a GameObject to attach DebugUiManager to with AddComponent. It doesn't have to be a dedicated one.
Then do the initialization in a script of your choice. In the sample, a class called Sample does it, attached to the gameObject that has the camera.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Kayac;
public class Sample : MonoBehaviour
{
[SerializeField]
GameObject _gameObjectForDebugUiManager;
[SerializeField]
Shader _textShader;
[SerializeField]
Shader _texturedShader;
[SerializeField]
Font _font;
[SerializeField]
Camera _camera;
DebugUiManager _debugUi;
DebugPrimitiveRenderer2D _renderer;
SampleWindow _sampleWindow;
void Start()
{
_renderer = new DebugPrimitiveRenderer2D(
_textShader,
_texturedShader,
_font,
_camera,
capacity: 8192); // maximum number of triangles
_debugUi = DebugUiManager.Create(
_gameObjectForDebugUiManager, // what was AddComponent-ed here is returned
_renderer);
_sampleWindow = new SampleWindow(_debugUi);
_debugUi.Add(_sampleWindow);
}
void Update()
{
_debugUi.ManualUpdate(Time.deltaTime);
}
void LateUpdate()
{
_renderer.LateUpdate();
}
}
You pass a shader for text, a shader for textured drawing, a font and a camera to create a DebugPrimitiveRenderer2D. The shaders come with the library. Then you create the DebugUiManager, passing it this DebugPrimitiveRenderer2D and the gameObject to attach the DebugUiManager to.
After that, you initialize as above, create your own window class and Add() it to the Manager, and do what's shown above in Update() and LateUpdate().
I gave DebugUiManager a ManualUpdate() that you have to call yourself because the execution order of the standard Update is undefined, which was a problem, and because Unity's event functions aren't free performance-wise. In the parts of Tokyo Prison I was responsible for, I avoided Update, Awake and Start as much as possible and had initialization and update functions called manually. That way the execution order is the same on every device, and there's no overhead. Parent-child relationships between objects can also be expressed straightforwardly in code. The debug UI is built this way to match that design.
However, if you don't mind Update's overhead and write things so they work in any execution order, plain Update may be the more proper Unity approach. Then it works just by placing it in the scene.
About drawing
Now let me roughly explain how the drawing works. Drawing is handled by DebugPrimitiveRenderer2D and its base, DebugPrimitiveRenderer. The 2D one has functions for generating 2D-specific shapes such as "rectangle", "circle" and "line", and the base class sets vertex data into a Mesh every frame and draws it with a CommandBuffer. Have you used functions like Mesh.SetVertices(), Mesh.SetUVs() and Mesh.SetColors()? Each character drawn generates six vertices, which are packed into arrays and passed to the Mesh with these functions. I use CommandBuffer purely out of personal taste, or rather as a learning exercise; there's no real reason for it. I think drawing normally with a MeshRenderer would be fine too.
Now, I said "one DrawCall", but that's when no textures are used. The SampleWindow above has only text and lines, so in this case it's one DrawCall no matter how much you draw. Lines, fills and so on are drawn using the texels in the middle of a square character in the font, '■', so there's no need to switch textures, and DrawCalls don't increase. The code that gets the texture coordinates of the middle of the square looks like this.
CharacterInfo ch;
_font.GetCharacterInfo('■', out ch);
_whiteUv = ch.uvTopLeft;
_whiteUv += ch.uvTopRight;
_whiteUv += ch.uvBottomLeft;
_whiteUv += ch.uvBottomRight;
_whiteUv *= 0.25f; // averaging the 4 vertices gives the center
If I could paste an arbitrary image into part of the font texture I wouldn't need a hack like this, but I couldn't find a way.
Among the classes that inherit DebugPrimitiveRenderer, there's also DebugPrimitiveRenderer3D. It's unrelated to this topic, but I use it to draw arrows, rectangles, strings, billboards and so on in a 3D game scene. For things like drawing the camera's focus range, showing extra information on characters, or showing information for each tile of the ground, being able to draw text and shapes in 3D space is handy. The published sample doesn't include code that uses it, but it's easy to use, so give it a try if you like. It can be used on its own, independently of DebugUiManager.
About input events
To press buttons and such, you need input. But what I made doesn't use gameObjects, so the usual UnityEngine.UI.Graphic features aren't available. Still, handling input through UnityEngine.UI.Graphic where possible would play better with other UI elements and seems easier to implement. So DebugUiManager alone inherits UnityEngine.UI.Graphic. Its RectTransform covers the whole screen with raycasting enabled, and that's how it gets input.
However, if it responds to input across the whole screen, it gets in the way of other UI elements (buttons and so on), so it must ignore input where there aren't actually any debug UI elements. For this, you implement UnityEngine.ICanvasRaycastFilter.IsRaycastLocationValid(). Like Update and Awake, it's one of those functions that, for whatever reason, takes effect when you implement it without override.
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
if ((_renderer == null) || !inputEnabled)
{
return false;
}
// If it hits something, take the event; if it hits nothing, let it through
float x = sp.x;
float y = sp.y;
ConvertCoordFromUnityScreen(ref x, ref y);
bool ret = false;
// Make it true while dragging. Otherwise various events can't be received
if (isDragging)
{
ret = true;
}
// true if it hits something
else if (_root.RaycastRecursive(0, 0, x, y))
{
ret = true;
}
else
{
// If it misses, treat it as released.
_input.isPointerDown = false;
_input.pointerX = -float.MaxValue;
_input.pointerY = -float.MaxValue;
ret = false;
}
return ret;
}
The controls form a tree, so it traverses depth-first from the root (_root) toward the leaves and returns true if the pointer is inside any control's rectangle. That's what DebugUiControl.RaycastRecursive() does. While dragging, however, it needs to return true even when the pointer is outside the control's rectangle.
Also, the coordinates are converted from screen coordinates to an internal virtual coordinate system before the test (ConvertCoordFromUnityScreen). The virtual resolution is set to, say, 1136x640, so that things take up the same proportion of the screen whether the device is 1920x1080 or 854x480. When the aspect ratio differs, it fits to the smaller dimension, so anything within the virtual resolution always fits on screen.
Thinking about it now, needing a Canvas just to get input events is a pain too. I don't actually use the Canvas for drawing, so it's inefficient as well. Maybe I should simply have set up a flat Collider and hooked it to the EventSystem with a PhysicsRaycaster.
Added 2019/2/1
I tried to get away from UnityEngine.UI in Unity 2018.3, but it didn't work out.
- I couldn't find a way to set the priority between Physics2DRaycaster and GraphicRaycaster; it seems the only way is to use multiple cameras.
- I couldn't find a way to control whether a Collider2D fires events, like IsRaycastLocationValid above.
Examples of derived controls
Buttons, toggles and everything else inherit DebugUiControl, and you can make new controls by inheriting it. There's also a control called DebugUiPanel, in which you can place multiple child controls (DebugUiWindow is a DebugUiPanel with a title bar).
So you can build quite a lot of things. As one example, let me introduce the "frame time gauge".
![]()
This one. The green bar corresponds to the number on the left, and the red bar to the number on the right. 21 means 21 milliseconds, "the average frame time over the last 60 frames". 44 means 44 milliseconds, "the time of the slowest frame in the last 60 frames". In other words, it shows processing speed and dropped frames as a gauge.
People have all kinds of opinions about what tool to build for monitoring frame rate and how to display it, but I like this approach. FPS (Frames Per Seconds), the number of frames per second, is easy to understand, partly because bigger is better, but it has the drawback that it's hard to tell "so how many more milliseconds do I need to shave off?" "FPS is 25, 5 short" and "FPS is 55, 5 short" call for completely different numbers of milliseconds to cut; the former is more than twice as hard as the latter. I find it more convenient to see at a glance "for 60FPS you need to stay under 16, and it's 22 now, so you're 6 milliseconds over". That's why I show it in milliseconds. Some people might show microseconds, but numbers displayed in real time don't need that much precision.
Also, showing "the maximum frame time over the last 60 frames" makes load spikes easy to notice. If you only show the average, you can't tell "mostly fine but one frame is slow" apart from "slow on average". The fixes are completely different, so it's better to be able to tell which it is.
This FrameTimeGauge inherits a basic control called DebugUiDualGauge, so it's fairly easy to make. It's included in the sample, so take a look if you like.
Incidentally, this gauge also appears in the product screenshot at the top of the article.
![]()
Unlike the sample, there's a second gauge labeled "API". It shows "the communication time of the last 10 API calls" and "the maximum time of the last 10 API calls". When something goes wrong, you can tell right away whether it might be a bug caused by network conditions.
If you can get memory usage, a gauge for that would be handy too. Unity itself can't provide it, but you should be able to with a native plugin, and I think it's worth the trouble.
I also made quite a few other features: a window that shows the current sound state for each channel, such as BGM, SE and voice (this also appears in the image at the top), a window showing the output of Debug.Log and Debug.LogWarning, implemented with DebugUiLogWindow (this appears too), a feature that graphs the battery level over time, and so on. Many of them depend on other modules, so I couldn't include them in the sample code, but if there's demand, I'd like to extract them cleanly and publish them as well.
Summary
So I made my own, and it works surprisingly well. I built it for my own use within my team, so I haven't shared it with other teams in the company, but Shihan , who sat next to me, used it quite a lot and even added a list box and such. It's funny that it's going public like this before it's even been shared inside the company.
The current limitations and bugs are roughly as follows.
- It's not very good-looking.
- I want anchors for placement. Right, left, center and so on.
- Features like automatic font sizing or sizing to fit the text are weak.
- Drawing breaks on the frame where the font texture fills up and is rebuilt.
- It redraws everything even when nothing has changed, so the load never goes down.
- I want good-looking graphs.
- I want to find designs for minimizing, moving and so on that suit smartphone touch controls.
All of these seem doable given the time, but it all comes down to time.
Also, one thing I'd like to do if I ever get a solid block of time is "move the display to a browser on another machine". A smartphone screen is small, and showing this kind of debug information on it gets in the way. If you run an http server inside the phone, connect from an external browser and draw this UI in that browser, you can mitigate this problem. You could also show the URL as a QR code on the device, use it to bring up the UI in a browser on a tablet or the like, and playtest while watching in-game information in real time. The steps (putting an http server on the device, defining the communication spec and writing the JS for the display) are clear, so I think I could do it if I put my mind to it.
Another direction is to take the drawing method I used here beyond the debug UI and apply it to features that ship in the product. For example, it could be used to implement a runtime that plays back data made in After Effects or Flash. UnityEngine.UI is optimized for things that "don't move much", and performance drops badly when vertices move. But what I made here "repacks all the vertices every frame", so the load stays the same however much things move. If I add a way to keep some vertices packed between frames, performance can go up further. For example, just caching string layouts should make it considerably faster. And since vertex generation doesn't use UnityEngine functions, it can be moved to another thread and parallelized. There seem to be plenty of ways to improve performance.
However, to use it for production drawing, you'd have to reduce DrawCalls by sorting by texture, support custom shaders, masks and so on, and the implementation and maintenance costs would shoot up. I suspect I'd get told off: "Don't roll your own, use what's already there". Leaving anything beyond a certain level of sophistication to the standard SpriteRenderer is probably the proper way to build things in Unity. The debug drawing I did here may be stretching what counts as reasonable use of Unity a little.
Next up is Gon with a talk about ARKit. Stay tuned!