Skip to content

Instantly share code, notes, and snippets.

@FlaShG
Last active January 20, 2023 07:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlaShG/49fcaf93bd8682a9722fd11950345b90 to your computer and use it in GitHub Desktop.
Save FlaShG/49fcaf93bd8682a9722fd11950345b90 to your computer and use it in GitHub Desktop.
Fix the display name when serializing property backing fields in Unity.
using UnityEngine;
/// <summary>
/// Use this attribute in combination with a [SerializeField] attribute on top of a property to display the property name. Example:
/// [field: SerializeField, UsePropertyName]
/// public int number { get; private set; }
/// </summary>
public class UsePropertyNameAttribute : PropertyAttribute
{
}
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(UsePropertyNameAttribute))]
public class UsePropertyNameAttributeDrawer : PropertyDrawer
{
// TODO Make useful for array properties
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.name.EndsWith("k__BackingField"))
{
FixLabel(label);
}
EditorGUI.PropertyField(position, property, label, true);
}
private static void FixLabel(GUIContent label)
{
var text = label.text;
var firstLetter = char.ToUpper(text[1]);
label.text = firstLetter + text.Substring(2, text.Length - 19);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment