Scroll so that the selected item is at the top of the list of drop-down items

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2020.3.25f1

Prerequisites for this tip

The following settings have been made in advance as a prerequisite for the explanation of these tips.

When displaying the drop-down item list, the top item is always displayed.

If the number of drop-down items is larger than the drop-down area, scrolling will be displayed, At that time, the first item displayed will always be the item at the top.

This is also true when the item at the bottom is selected and expanded.

However, some people may want the item they are selecting at the top of the list when expanded. To accommodate this, you need to configure the following additional settings:

Scroll so that the selected item is at the top when expanding the drop-down

This is done by a script. Add a script to your project and name it , DropdownScroll but the name is arbitrary.

When you open the Script Editor, enter the following:

using UnityEngine;
using UnityEngine.UI;    // 追加

public class DropdownScroll : MonoBehaviour
{
  public void Start()
  {
    // スクロールの計算に必要な各コンポーネントを取得
    var dropdown = GetComponentInParent<Dropdown>();
    var scrollRect = gameObject.GetComponent<ScrollRect>();
    var viewport = transform.Find("Viewport").GetComponent<RectTransform>();
    var contentArea = transform.Find("Viewport/Content").GetComponent<RectTransform>();
    var contentItem = transform.Find("Viewport/Content/Item").GetComponent<RectTransform>();

    // 選択しているアイテムの位置や表示領域をもとに選択アイテムまでスクロールすべき量を計算する
    var areaHeight = contentArea.rect.height - viewport.rect.height;
    var cellHeight = contentItem.rect.height;
    var scrollRatio = (cellHeight * dropdown.value) / areaHeight;
    scrollRect.verticalNormalizedPosition = 1.0f - Mathf.Clamp(scrollRatio, 0.0f, 1.0f);
  }
}

The content of the code is not that complicated. When the drop-down is expanded, the scrolling position is calculated and set so that the selected item is at the top.

Start The reason for writing it in the method is because it assumes that the initialization process will work every time the dropdown is expanded.

After you save the code, attach this Dropdown Template script to .

Temolate The objects under it are generated when the drop-down is expanded after the game is executed. The attached component is also initialized at the time of deployment. Also, when the drop-down is closed, the expanded object is destroyed, If you deploy it again, it will be generated again, so the initialization process will be executed after each deployment.

Let's try it.

As mentioned above, the drop-down that has not taken any action will not be visible even if you expand it with the item below selected. On the other hand, if you expand the drop-down that we addressed, you can see that it is scrolled to the point where you can see the selected item.