Search code examples
unity-game-engineunity-editor

Unity Editor : How to resize and space value field of an inspector property field?


I am trying to implement my first unity editor code to make a custom array property drawer with indented named entries and indented and dynamicaly resized value fields.

I am using the following simple git solution as base for my code, which allows to set the labels of an array in the inspector : HERE

replacing the example shown in the gitHub solution, I am working with this enum as my array element name container:

[System.Serializable]
public enum HealthNames
{
    General,
    Head,
    Body,
    RightArm,
    LeftArm,
    Rightleg,
    leftLeg,
}

and sets it up on a array in a monobehaviour class :

[ LabeledArray( typeof( HealthNames ) ) ]
public int[] m_aHealth = new int[ Enum.GetNames( typeof( HealthNames ) ).Length ];

I have added EditorGUI.indentLevel++; and EditorGUI.indentLevel--; at the start and end of the try statement to indent the label of the array elements, making them stand out from the size property.

enter image description here

Going from there, I have searched ways to add an indent on the elements' value fields or remove it from the size property's value field. but have found no answer using EditorGUI

I also looked to be able to resize all value fields dynamicaly, but there again, no answer came using EditorGUI only. there is no way to use EditorStyle.AnyField.WordWrap = true; on a propertyfield. Passing the PropertyField to an IntField, using a EditorStyles.NumberField and setting having its wrodwrapping set to true beforehand has no effect.

I also have found a small number of EditorGUILayout from a few years ago, but which do not work since the solution is built from the ground with EditorGUI

In hope of your enlightment on the matter


Solution

  • If I understand you correctly you want the labels and the value fields indented.

    I think it could be done like e.g.

    private const int INDENT = 15;
    
    public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(rect, label, property);
        var fieldsRect = new Rect(rect.x + INDENT, rect.y, rect.width - INDENT, rect.height);
        try
        {
            var path = property.propertyPath;
            int pos = int.Parse(path.Split('[').LastOrDefault().TrimEnd(']'));
            EditorGUI.PropertyField(fieldRect, property, new GUIContent(ObjectNames.NicifyVariableName(((LabeledArrayAttribute)attribute).names[pos])), true);
        }
        catch
        {
            EditorGUI.PropertyField(fieldRect, property, label, true);
        }
        EditorGUI.EndProperty();
    }