Unity_Set dropdown menu DropDown content

Realize the display of the drop-down menu content by customizing the name

In the editor, you can set the format of the drop-down content by setting the Template under DropDown

Setting the Options of the DropDown component can set the background image of the option, etc.

Our code is to add a listener to the component by obtaining the Options component under DropDown

OptionData is the content under Options, which contains two fields, Text and Image, we only change the text

Here is the full code: NameList is what you want to change in the drop-down box

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DropDownContent : MonoBehaviour
{
    public Dropdown marketDropDown;
    private List<string> NameLists;

    void Start()
    {
        NameLists = new List<string>();
        
        AddNames();

        UpdateDropDownView(NameLists);

        marketDropDown.gameObject.GetComponent<Dropdown>().onValueChanged.AddListener(ChangeMarketItem);
    }
    
    /// <summary>
    /// 用于添加信息到列表中
    /// </summary>
    private void AddNames()
    {
        string s1 = "全部";
        string s2 = "药品";
        string s3 = "饲料";
        string s4 = "材料";

        NameLists.Add(s1);
        NameLists.Add(s2);
        NameLists.Add(s3);
        NameLists.Add(s4);
    }

    /// <summary>
    /// 将数据更新到列表中
    /// </summary>
    /// <param name="showName"></param>
    private void UpdateDropDownView(List<string> showName)
    {
        marketDropDown.options.Clear();
        for (int i = 0; i < showName.Count; i++)
        {
            Dropdown.OptionData option = new Dropdown.OptionData();
            option.text = showName[i];
            marketDropDown.options.Add(option);
        }
        marketDropDown.captionText.text = showName[0];
    }
    /// <summary>
    /// 点击不同的选项,展示不同的内容
    /// </summary>
    /// <param name="index"></param>
    private void ChangeMarketItem(int index)
    {
        switch (index)
        {
            case 0 :
                Debug.Log("展示全部内容");
                break;

            case 1:
                Debug.Log("展示药品内容");
                break;

            case 2:
                Debug.Log("展示饲料内容");
                break;
                
            case 3:
                Debug.Log("展示材料内容");
                break;
            default: break;
        }
    }
}

Guess you like

Origin blog.csdn.net/leikang111/article/details/131306402