EditorGUI.PrefixLabel not aligning with other labels

HI everyone, still getting to grips with unity and running into trouble with EditorGUI.PrefixLabel when creating a custom property drawer. It’s not aligning correctly with other labels in the inspector for some reason.

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(HexCoordinates))]
public class HexCoordinatesDrawer : PropertyDrawer {

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

        HexCoordinates coordinates = new HexCoordinates(
            property.FindPropertyRelative("x").intValue,
            property.FindPropertyRelative("z").intValue);

        position = EditorGUI.PrefixLabel(position, label);
        GUI.Label(position, coordinates.ToString());
    }
}

My understanding is that using the following code should mean that the label is aligned with the “Script” label above, but instead I get this:

If I comment out position = EditorGUI.PrefixLabel(position, label);, then I get this instead, which surely means that the Rect is in the right place, and that the problem is with the PrefixLabel.

Very grateful for any and all help!

Sorry, should have said – Unity version 2019.4.21f1

Haha! I on this guide too.

I struggled with this same problem.

Fixed by replacing

position = EditorGUI.PrefixLabel(position, label);
GUI.Label(position, coordinates.ToString());

with

EditorGUI.LabelField(position, label.text, coordinates.ToString());
2 Likes

I just stumbled with this. It turns out that prefix label always expects a control id to be generated for it; when it doesn’t, all sort of bad things can happen. It’d be nice if the Editor prevented those bad things, or if we were warned when they happen, or if there was a mention of these pitfalls in the docs. Still, handling it correctly is very easy:

So, the best way to use it is to pass a controlID parameter.:

var controlID = GUIUtility.GetControlID(FocusType.Passive, position);
var fieldPosition = EditorGUI.PrefixLabel(position, controlID, label);

If you don’t want to use it, you should generate a control immediately after calling Prefix. You can do this by calling an interactive IMGUI control that you want to use with that label:

var fieldPosition = EditorGUI.PrefixLabel(position, label);
GUI.Button(fieldPosition, "a Button");

You can also do this by simply generating a ControlID after calling PrefixLabel.

var fieldPosition = EditorGUI.PrefixLabel(position, label);
GUIUtility.GetControlID(FocusType.Passive, fieldPosition);

That last example doesn’t seem like a good idea, though; it seems clearer and better for performance to pass the ID as a parameter, like in the first example.

2 Likes