开始制作好友系统了, 发现有一个UI跟QQ的面板一模一样. 于是就写了一个公共的下拉滚动框.需要把按钮的中心点(pivot.y = 1),描点为最上方 直接上图吧
代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.Events; public class DropScroll : MonoBehaviour { [SerializeField]
private Button[] btnList; //提供多个按钮
private RectTransform thisRT; [SerializeField]
private GameObject scrollViewTmp; //提供一个滚动视图模版
private List<RectTransform> scrollViewList = new List<RectTransform>(); public void Start()
{
Init();
} public void Init()
{
RectTransform rt = null; foreach (var btn in btnList)
{
EventTriggerListener.Get(btn.gameObject).OnClick += BtnDropClickEvent;
rt = GameObject.Instantiate(scrollViewTmp).GetComponent<RectTransform>();
scrollViewList.Add(rt);
rt.gameObject.SetActive(false);
rt.transform.SetParent(this.transform,false);
} thisRT = this.GetComponent<RectTransform>();
} private void BtnDropClickEvent(GameObject go)
{
RectTransform rt = go.GetComponent<RectTransform>();
RectTransform btnRt = null;
float height = thisRT.sizeDelta.y;
int index = rt.GetSiblingIndex(); HideAllScrollView();
scrollViewList[index].sizeDelta = new Vector2(thisRT.sizeDelta.x, height - btnList.Length * rt.sizeDelta.y);
scrollViewList[index].anchoredPosition = new Vector2(0, -((index + 1) * rt.sizeDelta.y));
scrollViewList[index].gameObject.SetActive(true); for (int i = 0; i < btnList.Length; i++)
{
btnRt = btnList[i].GetComponent<RectTransform>();
if (i > index)
{
btnRt.anchoredPosition = new Vector2(btnRt.anchoredPosition.x, -height + ((btnList.Length - i) * btnRt.sizeDelta.y));
}
else
{
btnRt.anchoredPosition = new Vector2(btnRt.anchoredPosition.x, -(i * btnRt.sizeDelta.y));
}
}
} private void HideAllScrollView()
{
for (int i = 0; i < scrollViewList.Count; i++)
{
scrollViewList[i].gameObject.SetActive(false);
}
}
} public class EventTriggerListener : UnityEngine.EventSystems.EventTrigger
{
public delegate void VoidDelegate(GameObject go);
public event VoidDelegate OnClick; static public EventTriggerListener Get(GameObject go)
{
EventTriggerListener listener = go.GetComponent<EventTriggerListener>(); if (listener == null)
listener = go.AddComponent<EventTriggerListener>(); return listener;
} public override void OnPointerClick(PointerEventData eventData)
{
if (OnClick != null)
OnClick(gameObject);
}
}
层次图: