Notes 丨 Unity implements button click events

1. First write a code file called "mainpannel" to manage all the buttons under the UI interface. After the writing is completed, the code is attached to the mainpannel object and instantiated. You can see that there is an additional component called Main pannel under the Inspector window.
Insert picture description here
2. Define a global variable in the code file, the object button_shiTou of the Button class.
Insert picture description here
3. After obtaining the stone button object component, add a listener on it to achieve the purpose of setting the button click event.
Insert picture description here
The following is the code segment and comments:

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

public class MainPanel : MonoBehaviour
{
    //创建一个Button类组件button_shiTou,用来存储石头按钮。
    Button button_shiTou;

    void Start()
    {
        //初始化石头按钮这个Button类对象,transform是Button类下的一个组件,可以调用Find函数,作用是找到MainPanel物体下的某个子物体,返回这个子物体
        //返回子物体后调用.GetComponent<Button>()获得Button_shiTou物体的Button组件。
        button_shiTou = transform.Find("button_shiTou").GetComponent<Button>();
        //onClick.AddListener()为石头按钮添加一个监听器,当该按钮被点击时将执行括号内的函数。
        button_shiTou.onClick.AddListener(OnShiTouButtonClick);
    }
    //当石头按钮被点击时触发此函数
    void OnShiTouButtonClick()
    {
        Debug.Log("砸缸按钮被点击!!!");
    }

At this time, the setting of the button click event has been completed.

Published 2 original articles · Likes0 · Visits 35

Guess you like

Origin blog.csdn.net/RoseM_ary/article/details/105534976