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

Managing UI State with Pseudo-Classes

You will implement hover, active, and focus states using USS pseudo-classes to create interactive and responsive user interface feedback.

In this lesson, you will learn how to use USS pseudo-classes to automatically trigger visual changes when a user interacts with your UI elements.

Understanding Pseudo-Classes

In standard CSS and Unity’s USS (Unity Style Sheets), a pseudo-class is a special keyword appended to a selector that defines the "state" of an element. Instead of writing complex C# scripts to manually change colors or sizes when a player clicks a button, you can let the UI system handle these transitions for you based on the user's interaction.

The three most common pseudo-classes you will use are:

  • :hover: Triggers when the mouse pointer is over the element.
  • :active: Triggers while the element is being clicked or held down.
  • :focus: Triggers when the element is currently selected (often via keyboard navigation or a click).

Implementation

To implement these, you define a base style for your element, then add blocks for each state in your .uss file. Unity automatically tracks these states for built-in components like Buttons.

/* Base Style */
.my-button {
    background-color: grey;
    transition: 0.2s background-color;
}

/* Hover State */
.my-button:hover {
    background-color: lightgrey;
}

/* Active State */
.my-button:active {
    background-color: darkgrey;
}

/* Focus State */
.my-button:focus {
    border-width: 2px;
    border-color: yellow;
}

By defining these states, your UI becomes "responsive." When a user hovers over the button, the USS engine detects the state change and instantly applies the styles within the :hover block. When the user moves the mouse away, the state resets automatically to the base class.

This approach is highly efficient because it keeps your logic inside the stylesheet rather than cluttering your C# scripts. It ensures a consistent look and feel throughout your application without requiring manual event polling for every minor visual adjustment.

Key Takeaway: Pseudo-classes allow you to define interactive UI behaviors declaratively, offloading state-based styling to the Unity Style Sheet engine for cleaner, more performant code.