Course contentsShow
← Unity Game Development
Lesson 317 of 8285. UI and Audio SystemsFree lesson

Exposing Custom Properties for Inspector Editing

You will create custom UI controls that expose specific styling properties to the Unity Inspector for easy design-time configuration.

In this lesson, you will learn how to bridge the gap between your custom UI code and the Unity Inspector, allowing you to configure component styles without touching the source code.

Why Expose Properties?

When you build a reusable custom UI control, you often want to tweak its visual style—like a button’s highlight color or a text element's font size—directly in the Unity Inspector. By default, your custom control's internal fields are invisible to the Inspector. To fix this, we expose them as public or [SerializeField] fields so that the Unity engine automatically creates an input field for us.

Exposing Properties for the Inspector

Suppose you are creating a HealthBar UI component. Instead of hardcoding the background color inside your C# class, you want to change it on the fly. You can declare public properties that allow the Inspector to "see" and modify these variables at design-time.

using UnityEngine;
using UnityEngine.UIElements;

public class HealthBar : VisualElement
{
    // By adding the [SerializeField] attribute, 
    // these values appear in the Inspector for your UI component
    [SerializeField] private Color barColor = Color.green;
    [SerializeField] private float thickness = 10f;

    public void ApplyStyle()
    {
        this.style.backgroundColor = barColor;
        this.style.height = thickness;
    }
}

The Workflow

  1. Define the field: Use private fields with the [SerializeField] attribute to ensure data remains encapsulated but editable by designers.
  2. Sync the Visuals: Since the Inspector only updates the variable value, you must trigger an update (or use a property setter) to ensure the UI element physically changes when the variable is modified.
  3. Inspector Integration: Unity detects these serializable fields and automatically renders a UI control in the Inspector window. You don’t need to write custom Inspector code just to display these values; the SerializeField attribute handles the heavy lifting.

This setup transforms your hard-coded UI elements into flexible, designer-friendly tools, significantly speeding up the iteration process when fine-tuning the look and feel of your game’s interface.

Key Takeaway: By using the [SerializeField] attribute on your UI component's variables, you instantly expose them to the Inspector, allowing for real-time design adjustments without modifying your underlying logic.