IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity 下拉菜单中【下拉列表自动加载】 以及 【读取当前item的值】 -> 正文阅读

[游戏开发]Unity 下拉菜单中【下拉列表自动加载】 以及 【读取当前item的值】

本文要解决的问题:


1、如何用代码初始化下拉菜单的item
2、如何乱序加载item
3、如何读取当前选中的item的值


在这里插入图片描述

一、下拉框外形——Dropdown

在这里插入图片描述

二、脚本的配置

在这里插入图片描述

三、功能实现

1、初始化Dropdown的下拉列表

/// <summary>
/// 增加一个【item菜单】
 /// </summary>
 /// <param name="strName"></param>
 void AddItmes(string strName)
 {
     //Make the index the last number of entries
     m_Index = m_Messages.Count;

     //Create a temporary option
     Dropdown.OptionData temp = new Dropdown.OptionData();

     //Make the option the data from the TextField
     temp.text = strName;

     //Update the messages list with the TextField data
     m_Messages.Add(temp);

     //Add the Textfield data to the Dropdown
     m_Dropdown.options.Insert(m_Index, temp);
 }

2、乱序排列一个列表

/// <summary>
/// 打乱list的item顺序
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
private List<T> RandomSort<T>(List<T> list)
{
    var random = new System.Random();
    var newList = new List<T>();
    foreach (var item in list)
    {
        newList.Insert(random.Next(newList.Count), item);
    }
    return newList;
}

3、读取当前的item

关键点:
获取当前项:
currentItem = GetComponent().options[idx].text

当前项的idx从哪里来:
idx = GetComponent().value

/// <summary>
/// onValueChanged绑定的方法:读取所选择的值
/// </summary>
void SetSelectedItem()
{
   var dp = dropDownGo.GetComponent<Dropdown>();
   var idx = dp.value;
   selectedItem = dp.options[idx].text;
   //TXDebug.Log(selectedItem);
}

四、代码清单

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

/// <summary>
/// 【下拉列表】控件的配套脚本
///     1、初始化下拉清单的值:面板上预先给定一个格式化的字符串,格式【苹果#香蕉#...】
///            特殊功能:使用【随机顺序】初始化下拉框
///        
///     2、暴露当前选中的值,供外部调用
///     备注:该脚本原型来自Unity官网demo
/// </summary>
public class DropDownController : MonoBehaviour
{
    /// <summary>
    /// 挂载dropdown组件的Gameobject
    /// </summary>
    [Header("挂载dropdown组件的Gameobject")]
    [SerializeField]
    public GameObject dropDownGo;

    /// <summary>
    /// 下拉菜单的品种,格式:【item1#item2#...】
    /// </summary>
    [Header("备选的选项【选项1#选项2#...】")]
    [SerializeField]
    public string items;

    /// <summary>
    /// 是否乱序加载:下拉框中的下拉元素是否乱序加载
    /// </summary>
    [Header("是否乱序加载")]
    [SerializeField]
    public bool randomSort;

    /// <summary>
    /// 当前被选中的项:string
    /// </summary>
    [Header("当前被选中的项")]
    [SerializeField]
    public string selectedItem;

    //Use these for adding options to the Dropdown List
    Dropdown.OptionData m_NewData, m_NewData2;

    //The list of messages for the Dropdown
    List<Dropdown.OptionData> m_Messages = new List<Dropdown.OptionData>();

    //This is the Dropdown
    Dropdown m_Dropdown;
    string m_MyString;
    int m_Index;

    private void OnEnable()
    {
        dropDownGo.GetComponent<Dropdown>().onValueChanged.AddListener(delegate { SetSelectedItem(); });
    }

    void Start()
    {
        //Fetch the Dropdown GameObject the script is attached to
        m_Dropdown = dropDownGo.GetComponent<Dropdown>();

        //Clear the old options of the Dropdown menu
        m_Dropdown.ClearOptions();

        //加载下拉元素:乱序或者正常顺序
        var finItems = randomSort ?
            RandomSort(items.Split('#').ToList()).ToArray() : items.Split('#');
        LoadItems(finItems);//初始化的时候,为空

        selectedItem = finItems[0];
    }

    /// <summary>
    /// 增加一个【item菜单】
    /// </summary>
    /// <param name="strName"></param>
    void AddItmes(string strName)
    {
        //Make the index the last number of entries
        m_Index = m_Messages.Count;

        //Create a temporary option
        Dropdown.OptionData temp = new Dropdown.OptionData();

        //Make the option the data from the TextField
        temp.text = strName;

        //Update the messages list with the TextField data
        m_Messages.Add(temp);

        //Add the Textfield data to the Dropdown
        m_Dropdown.options.Insert(m_Index, temp);
    }

    /// <summary>
    /// 加载所有item
    /// </summary>
    /// <param name="ary">字符串数组</param>
    void LoadItems(string[] ary)
    {   
        ary.ToList().ForEach(x=>AddItmes(x));
    }  

    //private void Update()
    //{
    //    if (Input.GetKeyDown(KeyCode.Return))
    //    {
    //        //生成乱序的列表  ----测试----
    //        TXDebug.Log("-------------------------------------------");
    //        items.Split('#').ToList().ForEach(x => TXDebug.Log(x));
    //        TXDebug.Log("-------------------------------------------");
    //        RandomSort(items.Split('#').ToList()).ForEach(x => TXDebug.Log(x));
    //    }
    //}

    /// <summary>
    /// onValueChanged绑定的方法:读取所选择的值
    /// </summary>
    void SetSelectedItem()
    {
        var dp = dropDownGo.GetComponent<Dropdown>();
        var idx = dp.value;
        selectedItem = dp.options[idx].text;
        //TXDebug.Log(selectedItem);
    }

    /// <summary>
    /// 打乱list的item顺序
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    private List<T> RandomSort<T>(List<T> list)
    {
        var random = new System.Random();
        var newList = new List<T>();
        foreach (var item in list)
        {
            newList.Insert(random.Next(newList.Count), item);
        }
        return newList;
    }
}
  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章           查看所有文章
加:2022-01-01 14:17:32  更:2022-01-01 14:20:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年9日历 -2024/9/25 6:17:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码