Too much space between EditorGUILayout.SelectableLabel

I want to place selectable text into custom EditorWindow.

Here is my code:

using UnityEditor;
using UnityEngine;
using System;

public class MyEditorWindow : EditorWindow
{
    Vector2 scrollPosition = Vector2.zero;

    [MenuItem("Window/MyEditorWindow")]
    public static void ShowExample()
    {
        var wnd = GetWindow<MyEditorWindow>();
        wnd.titleContent = new GUIContent("MyEditorWindow");
    }

    private void OnGUI()
    {
        scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(position.width), GUILayout.Height(position.height));

        var elapsed = new TimeSpan();
        for (int i = 0; i < 100; i++)
        {
            elapsed = elapsed.Add(TimeSpan.FromSeconds(1));
        }

        for (int i = 0; i < 100; i++)
        {
            EditorGUILayout.SelectableLabel("Some long long long long text");
        }

        GUILayout.EndScrollView();
    }
}

It works, but there is too much space between the lines:
alt text

How to make it smaller?

The EditorGUILayout.SelectableLabel is defined like this:

public static void SelectableLabel(string text, GUIStyle style, params GUILayoutOption[] options)
{
    Rect position = EditorGUILayout.GetControlRect(false, 32f, style, options);
    EditorGUILayout.s_LastRect = position;
    EditorGUI.SelectableLabel(position, text, style);
}

As you can see it allocates a fix layout rectangle of 32 pixels height. It does not adjust to the content. You essentially have two options:

  • use GUILayout.Height() to define a fix height for the label (default single line height is usually 15).
  • allocate the rect for the control yourself and use EditorGUI.SelectableLabel

Keep in mind that if you draw too many things in OnGUI it will have a huge impact on the performance of the editor. 100 items shouldn’t be too bad, however 500+ will probably be and issue.

An implementation of what @Bunny83 suggested ("allocate the rect for the control yourself "). For those in need of a quick copy n paste Solution :wink:

public static void DrawSelectableLabel(string text, GUIStyle style = null)
{
	if (style == null)
		style = GUI.skin.label;
	
	var content = new GUIContent(text);
	var position = GUILayoutUtility.GetRect(content, style);
	EditorGUI.SelectableLabel(position, text, style);
}