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
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961