You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何获取List<Button>列表内被点击按钮的索引?

获取List

这里提供几种实用的实现方式,根据你的场景选择即可:

方法1:利用Button的Tag属性存储索引

在初始化按钮并添加到列表时,把当前索引存入按钮的Tag属性,点击时直接读取:

// 示例:批量创建按钮并添加到列表
int buttonCount = 5; // 假设要创建5个按钮
for (int i = 0; i < buttonCount; i++)
{
    Button btn = new Button();
    btn.Text = $"按钮{i+1}";
    btn.Tag = i; // 将当前索引存入Tag
    btn.Click += Button_Click;
    buttonList.Add(btn);
    this.Controls.Add(btn); // 添加到窗体或容器
}

// 点击事件处理方法
private void Button_Click(object sender, EventArgs e)
{
    if (sender is Button clickedBtn && clickedBtn.Tag is int index)
    {
        // 成功获取索引,后续逻辑写在这里
        Console.WriteLine($"点击的按钮索引:{index}");
    }
}

方法2:通过闭包捕获索引

绑定点击事件时,用局部变量捕获当前循环的索引,避免闭包陷阱:

int buttonCount = 5;
for (int i = 0; i < buttonCount; i++)
{
    Button btn = new Button();
    btn.Text = $"按钮{i+1}";
    int currentIndex = i; // 用局部变量保存当前索引,避免循环变量引用问题
    btn.Click += (s, e) => 
    {
        Console.WriteLine($"点击的按钮索引:{currentIndex}");
    };
    buttonList.Add(btn);
    this.Controls.Add(btn);
}

方法3:使用List的IndexOf方法

直接通过列表的IndexOf方法查找点击的按钮实例,前提是按钮在列表中唯一存在:

// 先给所有按钮绑定同一个点击事件
foreach (Button btn in buttonList)
{
    btn.Click += Button_Click;
}

// 点击事件处理
private void Button_Click(object sender, EventArgs e)
{
    if (sender is Button clickedBtn)
    {
        int index = buttonList.IndexOf(clickedBtn);
        if (index != -1) // 确保按钮存在于列表中
        {
            Console.WriteLine($"点击的按钮索引:{index}");
        }
    }
}

各方法优缺点说明

  • Tag属性法:兼容性强,适用于所有.NET版本,无需担心闭包问题,但需要额外存储数据。
  • 闭包捕获法:代码简洁,无需额外属性存储,但要注意循环变量的闭包陷阱(必须用局部变量保存当前索引)。
  • IndexOf法:无需提前存储索引,直接通过实例查找,但如果列表中有重复的Button实例(极少出现),会返回第一个匹配的索引。

内容的提问来源于stack exchange,提问作者redokum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:15:41