【UGUI】如何获取当前点击Button的名称及数字部分

        在Unity中获取当前点击按钮的名称及数字部分可以通过以下步骤:

        第一步,新建Canvas,并添加Image(GameObject > UI > Image),给Image添加一个Button组件(Add Component > Button),如下图所示。

        第二步,在脚本中创建一个公共方法,并将其附加到按钮的OnClick()事件上。在Unity编辑器中选中按钮,在Inspector视图中找到OnClick()事件,然后将脚本中创建的公共方法拖放到事件列表中,当然可以和博主一样,将脚本拖放给Canvas,再通过拖拽Canvas获取脚本及方法。

        代码如下,包括了获取当前点击Button数字部分完整代码,以下将进行介绍:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ButtonTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void OnClick()
    {
        GameObject clickedButton = EventSystem.current.currentSelectedGameObject;
        Button button = clickedButton.GetComponent<Button>();
        Debug.Log("当前Button的名称:" + button.name);
        string buttonName = button.name; //获取按钮名称
        string numberString = buttonName.Substring("Button".Length); //获取数字部分
        int number = int.Parse(numberString); //将字符串转换为整数
        Debug.Log("当前Button的数字部分:" + number);
    }
}

        在上面的代码中,OnClick()方法是一个公共方法,将被附加到按钮的OnClick()事件上。在该方法中,使用EventSystem.current.currentSelectedGameObject获取当前选中的GameObject,然后使用GetComponent()方法获取Button组件。最后,使用Button组件上的属性和方法来处理按钮点击事件。在这个例子中,我们只是简单地在控制台中打印了被点击的按钮的名称。

        如果小伙伴们想要获取当前点击按钮的数字部分,可以使用字符串操作来获取数字部分。在上面的代码中,我们首先获取按钮的名称,然后使用Substring()方法获取名称中的数字部分。这个数字部分是一个字符串类型的数据,所以我们使用int.Parse()方法将它转换为整数类型的数据。

        特别注意,上面的代码假定所有的按钮名称都以"Button"开头,数字部分紧随其后,并且需要将脚本附加到所有按钮的OnClick()事件上。如果小伙伴们的按钮名称格式不同,可以更改OnClick()公共方法中第5行代码中的Button进行实现。

猜你喜欢

转载自blog.csdn.net/m0_51942776/article/details/130332908