In this lesson, you will learn how to use USS pseudo-states to make your UI feel responsive by changing its appearance based on player interaction.
What are Pseudo-States?
When a player interacts with a UI element—like hovering a mouse cursor over a button or clicking it—the element enters a temporary "state." In Unity’s UI Toolkit, we use pseudo-states to define specific styles that only trigger when these interactions occur. Instead of writing complex C# scripts to toggle colors, we can define these transitions directly in our USS (Unity Style Sheet) files.
There are three primary pseudo-states we use for basic interactivity:
:hover: Triggered when the pointer is inside the element’s bounds.:active: Triggered while the element is being clicked or held down.:focus: Triggered when the element is selected (e.g., via keyboard navigation or a click).
Implementing Interactive Styles
To implement these, you append the state to your selector in the USS file. The base style defines the "default" look, while the pseudo-states define the "feedback" look.
.my-button {
background-color: gray;
transition: 0.2s background-color; /* Smooths the visual change */
}
/* Change color when hovering */
.my-button:hover {
background-color: lightgray;
}
/* Darken when clicked */
.my-button:active {
background-color: darkgray;
}
/* Add a border when the button is focused */
.my-button:focus {
border-width: 2px;
border-color: yellow;
}
By defining these in your USS, you ensure that the UI responds instantly to the player's actions without manual event handling. If the player moves their mouse away, the state automatically reverts to the default style, keeping your code clean and your UI feel polished. Remember to always provide enough contrast so the player knows exactly which element they are interacting with.
Key Takeaway: Use USS pseudo-states like :hover, :active, and :focus to create reactive, intuitive UI feedback that informs the player of their current interaction state without the need for additional C# logic.