[UGUI] Add a callback function to the Button component - that is, the button controls some behaviors

[UGUI] Add a callback function to the Button component - that is, the button controls some behaviors

The first one: add a listening event - get the Button - associate the code with a function

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

public class UIcontrol : MonoBehaviour
{
    // 演示组件控制
    //1.拿到整个游戏物体 2.拿到组件 3.获取用选中的数值 
    GameObject ONEBTobj;//拿到按钮 !类的变量,类的实例化对象
    Button ButtonComp;//拿到按钮组件!类的变量,类的实例化对象
    public GameObject Image1;//拿到一个图片

    void Start()
    {
        
        Image1.SetActive(false);//游戏开始让图片关闭
        
        ButtonComp.onClick.AddListener(ClickButton);//为按钮添加一个关联的函数!-委托事件
    }
    public void ClickButton()
    {
        Debug.Log("点击按钮!开始游戏了");
        if (Image1.activeSelf)
        {
            Image1.SetActive(false);
        }
        else
        {
            Image1.SetActive(true);
        }
    }


}

Second method: Customize a Public function and add it in the component properties

First create a public function in the script arbitrarily

Then hang it externally in the Onclick() list under the button component, click the plus sign, and add the callback function!

If you want to find the function, you need to find the script. If you want to find the script, you need to find the game object where the script is located!

So put the game object where the script where the public function we defined is located is placed!

Guess you like

Origin blog.csdn.net/leoysq/article/details/134736960