一,前言
unity自带的dropdown我一直觉得用着太费劲 调整不好调整的 灵活性太低为此我自定义了个droplist 如下:
二 原理讲解
折叠状态:default options隐藏
首先需要做一个折叠时候的显示 图片 文字 选中框 具体可以自行diy 我这里图片是全铺于父物体 如此我们调整droplist大小即可实现调整 折叠状态显示内容
down up 是右侧三角符号 用于展示当前是否打开下拉列表 入不需要可自行去掉
Options 选项
Droplist 是一个模板 是展开后的选项生成的模板 所以只需要做好这一个模板即可
list 是用于排列下拉框的所以需要如下组件:
三 代码实现:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
[Serializable]
public class OnClick : UnityEvent { }
public class DropList : MonoBehaviour {
public GameObject optionsTr;//选项列表
public GameObject currentChoose;//当前选项框
public bool listShow = false;//列表是否已经打开
public OnClick onshow,onhide;//点击事件
public Sprite chooseIcon;//选择框
public GameObject listItemPre;//选项预制体
public Transform listGrid;//选项列表
public Text defaultTex;
/// <summary>
/// 初始化
/// </summary>
/// <param name="names"></param>
public void InitDropList(List<string> names)
{
for (int i = 0; i < names.Count; i++)
{
GameObject item = Instantiate(listItemPre, listGrid);
int index = i;
item.GetComponentInChildren<Button>().onClick.AddListener(() =>
{
if (currentChoose != null) currentChoose.SetActive(false);
defaultTex.text = names[index];
currentChoose = item.transform.GetChild(1).gameObject;
currentChoose .SetActive(true);
ShowList();
});
item.GetComponentInChildren<Text>().text = names[i];
if(i == 0)
{
defaultTex.text = names[i];
currentChoose = item.transform.GetChild(1).gameObject;
currentChoose.SetActive(true);
}
item.SetActive(true);
}
optionsTr.SetActive(false);
listGrid.GetComponent<VerticalLayoutGroup>().enabled = true;
}
/// <summary>
/// 显示列表
/// </summary>
public void ShowList()
{
listShow = !listShow;
if(listShow)
{
onshow.Invoke();
optionsTr.SetActive(true);
}
else
{
onhide.Invoke();
optionsTr.SetActive(false );
}
}
}
此外我增加了事件监听 可以在面板上添加 列表打开和关闭的额外事件