Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Show the `ToString()` of a MonoBehavior in the preview GUI.
/* Original code[1] Copyright (c) 2019 Shane Celis[2]
Licensed under the MIT License[3]
This comment generated by code-cite[4].
using UnityEngine;
using UnityEditor;
/** PreviewGuiEditor shows the `ToString()` of a MonoBehavior in the preview GUI
as demonstrated in this tweet[1]. Will work with any component. Just add an
attribute to this editor like so:
Will also work with any component that implements IRichString. Advise
placing the interface into a `Scripts` folder rather than an `Editor`
Modeled after Unity's EventSystemEditor[2].
// [CustomEditor(typeof(YourType))]
[CustomEditor(typeof(Objective), true)]
public class PreviewGUIEditor : Editor {
/** Update every 15th frame. */
private const int updateOnFrame = 15;
private GUIStyle _previewLabelStyle;
protected GUIStyle previewLabelStyle {
get {
if (_previewLabelStyle == null) {
_previewLabelStyle = new GUIStyle("PreOverlayLabel") {
richText = false,
alignment = TextAnchor.UpperLeft,
fontStyle = FontStyle.Normal
// Try to get a fixed-width font on macOS.
var font = Font.CreateDynamicFontFromOSFont("Monaco", 12);
// Failing that, try to get a fixed-width font on Windows.
if (font == null)
font = Font.CreateDynamicFontFromOSFont("Lucida Console", 12);
// XXX What fixed-width font should I request if we're on Linux?
if (font != null)
_previewLabelStyle.font = font;
// Debug.Log("Fonts: \n" + string.Join("\n", Font.GetOSInstalledFontNames()));
return _previewLabelStyle;
public override bool HasPreviewGUI() {
return Application.isPlaying;
public override bool RequiresConstantRepaint() {
// Only repaint on the nth frame.
return Application.isPlaying && Time.frameCount % updateOnFrame == 0;
public override void OnPreviewGUI(Rect rect, GUIStyle background) {
// Cast to more specialized type if necessary.
string str;
var richString = target as IRichString;
if (richString != null) {
str = richString.ToRichString();
previewLabelStyle.richText = true;
} else if (target != null) {
str = target.ToString();
previewLabelStyle.richText = false;
} else {
// No string available to preview.
string str = target.ToString();
GUI.Label(rect, str, previewLabelStyle);
/** This interface provides a string that is marked up with Unity's rich string
format[3], e.g., <b> for bold, <i> for italics, etc.
May need to copy and paste this interface into `IRichString.cs` in a
`Scripts` folder (not `Editor`).
public interface IRichString {
string ToRichString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment