using System; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; /// /// 数字选择器 /// public class NumPicker : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public int maxNum; public int minNum; public int _itemNum = 5; [HideInInspector] /// /// 更新选择的目标值 /// public float _updateLength; /// /// 子节点预制体 /// public GameObject _itemObj; /// /// 子节点容器对象 /// public Transform _itemParent; public Color normalColor; public int value; public Action onValueChange; void Awake() { _itemObj.SetActive(false); _updateLength = _itemObj.GetComponent().sizeDelta.y/2; } private void Start() { // Init(10); } /// /// 初始化数字选择器 /// public void Init(int num, Action onValueChange) { this.onValueChange = onValueChange; value = num; for (int i = 0; i < _itemNum; i++) { //计算真实位置 int real_i = -(_itemNum / 2) + i; SpawnItem(real_i); } RefreshDateList(); } /// /// 生成子对象 /// /// 真实位置 /// GameObject SpawnItem(float real_i) { GameObject _item = Instantiate(_itemObj); _item.SetActive(true); _item.transform.SetParent(_itemParent); _item.transform.localScale = Vector3.one; _item.transform.localEulerAngles = Vector3.zero; _item.transform.localPosition = Vector3.zero; if (real_i != 0) { _item.GetComponent().color = normalColor; // _item.transform.eulerAngles += new Vector3(20 * Mathf.Abs(real_i), 0, 0); _item.GetComponent().sizeDelta -= new Vector2(0, 80); // _item.GetComponent().fontSize -= 30; //_item.GetComponent().fontStyle = FontStyle.Normal; } return _item; } Vector3 oldDragPos; /// /// 当开始拖拽 /// /// public void OnBeginDrag(PointerEventData eventData) { oldDragPos = eventData.position; } public void OnDrag(PointerEventData eventData) { UpdateSelectDate(eventData); } public void OnEndDrag(PointerEventData eventData) { _itemParent.localPosition = Vector3.zero; } /// /// 更新选择的数字 /// /// void UpdateSelectDate(PointerEventData eventData) { //判断拖拽的长度是否大于目标值 if (Mathf.Abs(eventData.position.y - oldDragPos.y) >= _updateLength) { int num; //判断加减 if (eventData.position.y > oldDragPos.y) { //+ num = (int)(Mathf.Abs(eventData.position.y - oldDragPos.y) / _updateLength); } else { //- num = -(int)(Mathf.Abs(eventData.position.y - oldDragPos.y) / _updateLength); } value += num; //判断是否属于时间段 if (IsInRange(value)) { oldDragPos = eventData.position; RefreshDateList(); } else { value -= num; RefreshDateList(); } onValueChange?.Invoke(value); _itemParent.localPosition = Vector3.zero; } else { _itemParent.localPosition = new Vector3(0, (eventData.position.y - oldDragPos.y), 0); } } /// /// 刷新时间列表 /// public void RefreshDateList() { for (int i = 0; i < _itemNum; i++) { //计算真实位置 int real_i = -(_itemNum / 2) + i; string str = ""; if (IsInRange(value+ real_i)) { int nowvalue=value+real_i; if(nowvalue<10) str ="0"+nowvalue; else str=nowvalue.ToString(); } _itemParent.GetChild(i).GetComponent().text = str; } } public bool IsInRange(int value) { return value>=minNum &&value<=maxNum ; } }