123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Events;
- using UnityEngine.UI;
- [RequireComponent(typeof(Button))]
- public class customDropDown : MonoBehaviour
- {
- public Text label;
- public GameObject dropmenu;
- public GameObject template;
- public GameObject contentParent;
- [SerializeField]
- private List<string> options;
- public UnityEvent OnChangedValue;
- public int selectedIndex;
- public void SetValue(int value){
- selectedIndex = value;
- RefreshMenu();
- }
- public void SetOptions(List<string> _options){
- options = _options;
- RefreshMenu();
- }
- public void RemoveOption(string item){
- options.Remove(item);
- RefreshMenu();
- }
- public void AddOption(string item){
- options.Add(item);
- RefreshMenu();
- }
- public List<string> GetOptions(){
- return options;
- }
- public int GetOption(string value){
- for(int i =0; i < options.Count; i++){
- if(options[i] == value){return i;}
- }
- return 0;
- }
- public void toggleDropmenu(){
- if(!dropmenu.activeSelf){
- RefreshMenu();
- }
- dropmenu.SetActive(!dropmenu.activeSelf);
-
- }
- List<GameObject> items;
- public void RefreshMenu(){
- //clean the list before adding new items
- Transform[] children = contentParent.transform.GetComponentsInChildren<Transform>();
- foreach(Transform child in children){
- if(child != contentParent.transform && child != template.transform){
- Destroy(child.gameObject);
- }
- }
- if(items==null){items = new List<GameObject>();}
- items.Clear();
- //all clear; let's go
-
- for(int i =0; i < options.Count; i++){
- string option = options[i];
- GameObject item = Instantiate(template, contentParent.transform);
- try{
- item.SetActive(true);
- item.transform.GetChild(0).GetComponent<Image>().enabled=i == selectedIndex;
- item.transform.GetChild(1).GetComponent<Text>().text = option;
- }catch{}
- int curIndex =i;
- item.GetComponent<Button>().onClick.AddListener(()=>{_onSelectedOption(curIndex);});
- items.Add(item);
- if(selectedIndex ==i){
- label.text = option;
- }
- }
- label.text = options[selectedIndex];
- }
- private void _onSelectedOption(int id){
- selectedIndex=id;
- for(int i =0; i < items.Count; i++){
- if(i != id){
- items[i].transform.GetChild(0).GetComponent<Image>().enabled=false;
- }else{
- items[i].transform.GetChild(0).GetComponent<Image>().enabled = true;
- }
- }
- dropmenu.SetActive(false);
- label.text = options[id];
- OnChangedValue.Invoke();
- }
- void Start()
- {
- GetComponent<Button>().onClick.AddListener(toggleDropmenu);
- template.SetActive(false);
- RefreshMenu();
- dropmenu.SetActive(false);
- }
- }
|