Unity UGUI动态创建按钮列表并赋予按钮点击事件,思路是:先在UI上拖放一个Button,然后动态克隆这个Button。
实现方法:在Canvas放置一个Image控件,一个Panel(命名为Panel_Button),一个Button,一个Scrollbar,关系如下图:
Button是我们克隆的对象,不需要显示出来,所以scale设置为0:
为Panel_Button添加Vertical Layout Group组件,设置如下:
Scrollbar设置Direction为Bottom To Top,移动到Panel_Button右侧:
为Image添加Scroll Rect组件,Content赋值为Panel_Button,勾选Vertical,取消Horizontal,Movement Type设置为Unrestricted:
为Image创建Mask组件:
代码部分:
新建AddButton.cs并挂载到Canvas下面:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AddButton : MonoBehaviour
{
public GameObject go;
// Start is called before the first frame update
void Start()
{
int btnPos = 0; //第一个Button的Y轴位置
int btnHeight = 30; //Button的高度
int btnCount = 100; //Button的数量
GameObject panel_button = GameObject.Find("Panel_Button");
var rectTransform = panel_button.transform.GetComponent<RectTransform>();
panel_button.transform.localPosition = new Vector3(0, 0-(((btnHeight * btnCount)/2)-(rectTransform.rect.height/2)), 0);
rectTransform.sizeDelta = new Vector2 (rectTransform.rect.width, btnHeight * btnCount);
for(int i = 0; i < btnCount; i++)
{
string text = i.ToString();
GameObject goClone = Instantiate(go);
goClone.transform.parent = panel_button.transform;
goClone.transform.localScale = new Vector3(1, 1, 1); //由于克隆的Button缩放被设置为0,所以这里要设置为1
goClone.transform.localPosition = new Vector3(0, btnPos, 0);
goClone.transform.Find("Text").GetComponent<Text>().text = text;
goClone.GetComponent<Button>().onClick.AddListener
(
() =>
{
Click(text); //添加按钮点击事件
}
);
//下一个Button的位置等于当前减去他的高度
btnPos = btnPos - btnHeight;
}
}
void Click(string text)
{
Debug.Log(text);
}
}
最终效果:
点击事件: