Version: 2023.2
Create a custom control with two attributes
Create a bindable custom control

Create a slide toggle custom control

Version: 2023.2+

This example demonstrates how to create a “switch-like” variation of a toggle.

Example overview

The example creates a custom control: a toggle that users can flip with the mouse, the keyboard, a gamepad, and other devices. It comes with a label that can describe what the toggle represents.

You can find the completed files that this example creates in this GitHub repository.

先决条件

This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:

Create the slide toggle class

Create the slide toggle class with a C# script.

  1. Create a Unity project with the 3D template. A 3D template has a better visual effect for this example. However, you can use any template.
  2. Create a folder named slide-toggle to store your files.
  3. In the slide-toggle folder, create a C# script named SlideToggle.cs.
  4. Open SlideToggle.cs in a text editor and replace its content with the following:

[!code-cs]

Style the slide toggle

Style the slide toggle with a USS file.

  1. In the slide-toggle folder, create a USS file named SlideToggle.uss.
  2. Open SlideToggle.uss in a text editor and replace its contents with the following:

[!code-css]

Add a slide toggle to a UXML file with the UI Builder

  1. In the slide-toggle folder, create a UI Document file named SlideToggleUsage.uxml.
  2. Open SlideToggleUsage.uxml in the UI Builder.
  3. In the UI Builder, select Library > Project > MyUILibrary.
  4. Drag a SlideToggle into the Hierarchy window.
  5. In the Inspector, enter a label text for your toggle in the Label field.
  6. In the StyleSheets section, add SlideToggle.uss as the existing USS.
  7. Save and close the UI Builder.

Test the slide toggle

  1. In the SampleScene, create a UI Document GameObject.
  2. Select the UI Document, and drag SlideToggleUsage.uxml into the Source Asset field in the Inspector.
  3. Enter play mode. You can click on the toggle, press Enter, press Return, or press Space and get it to flip back and forth.

其他资源

Create a custom control with two attributes
Create a bindable custom control