- Unity 2018 Cookbook(Third Edition)
- Matt Smith
- 345字
- 2025-02-23 18:56:38
How to do it...
To create a UI Dropdown control GameObject, follow these steps:
- Create a new Unity 2D project.
- Add UI Dropdown to the scene.
- In the Inspector, for the Dropdown (Script) component, change the list of Options from Option A, Option B, and Option C to Hearts, Clubs, Diamonds, and Spades. You'll need to click the plus (+) button to add space for the fourth option of Spades.
- Add an instance of the C# script class called DropdownManager to the Dropdown GameObject:
using UnityEngine; using UnityEngine.UI; public class DropdownManager : MonoBehaviour { private Dropdown dropdown; private void Awake() { dropdown = GetComponent<Dropdown>(); } public void PrintNewValue() { int currentValue = dropdown.value; print ("option changed to = " + currentValue); } }
- With the Dropdown GameObject selected, add an On Value Changed event to the list of event handlers for the Dropdown (Script) component, click on the plus (+) button to add an event-handler slot, and drag Dropdown into the Object slot.
- From the Function drop-down menu, choose DropdownManager and then choose the PrintNewValue method.
- Save and run the Scene. Each time you change the Dropdown, the On Value Changed event will fire, and you'll see a new text message printed into the Console window by our script, stating the Integer index of the chosen Dropdown value (0 for the first item, 1 for the second item and so on):

- Select the Template child GameObject of the Dropdown in the Project panel, and in its Rect Transform reduce its height to 50. When you run the Scene, you should see a scrollable area, since not all options fit within the Template's height:

- Delete the Scrollbar child of the Template GameObject, and remove the Scroll Rect (Script) component of the Template GameObject. When you run the Scene now, you'll only see the first two options (Hearts and Clubs), with no way to access the other two options. When you are sure your Template's height is sufficient for all its options, you can safely remove these scrollable options to simplify the GameObjects in your scene.