检查是否在特定的UI元素上单击了鼠标? [英] Check if mouse was clicked over specific UI elements?

查看:81
本文介绍了检查是否在特定的UI元素上单击了鼠标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EventSystem.current.IsPointerOverGameObject()检查是否在任何UI元素上单击了鼠标.如何检查鼠标是否在 特定 UI元素(2个或3个按钮)上单击?我想使用标签并继续使用EventSystem.current.IsPointerOverGameObject()

EventSystem.current.IsPointerOverGameObject() checks if the mouse was clicked over any UI element. How can I check if the mouse was clicked over specific UI elements (2 or 3 buttons)? I would like to use tags and keep using EventSystem.current.IsPointerOverGameObject()!

推荐答案

您不使用EventSystem.current.IsPointerOverGameObject()来读取按钮单击.

You don't use EventSystem.current.IsPointerOverGameObject() to read button clicks.

您可以在OnEnable()函数中用Button.onClick.AddListener(() => callbackfunctionName());注册Button事件.

You register Button events with Button.onClick.AddListener(() => callbackfunctionName()); in the OnEnable() function.

然后使用Button.onClick.RemoveAllListeners();

由于大约需要3个Buttons,所以我没有使用Button的多个回调函数,而是仅使用一个以Button作为参数的函数.然后,我使用if语句检查按下了哪个Button.这是最好的方法,因为它减少了代码中的函数数量.

Since you need about 3 Buttons, instead of having multiple callback functions for the Button, I use only one function that takes Button as a parameter. I then use if statement to check which Button is pressed. This is the best way to do it as it reduces number of functions in your code.

将下面的脚本附加到GameObject,然后将这些按钮拖到button1button2button3插槽.

Attach the Script below to a GameObject then Drag those Buttons to the button1,button2 and button3 slots.

using UnityEngine;
using UnityEngine.UI;

public class ButtonChecker: MonoBehaviour
{

    public Button button1;
    public Button button2;
    public Button button3;

    void OnEnable()
    {
        //Register Button Events
        button1.onClick.AddListener(() => buttonCallBack(button1));
        button2.onClick.AddListener(() => buttonCallBack(button2));
        button3.onClick.AddListener(() => buttonCallBack(button3));

    }

    private void buttonCallBack(Button buttonPressed)
    {
        if (buttonPressed == button1)
        {
            //Your code for button 1
        }

        if (buttonPressed == button2)
        {
            //Your code for button 2
        }

        if (buttonPressed == button3)
        {
            //Your code for button 3
        }
    }

    void OnDisable()
    {
        //Un-Register Button Events
        button1.onClick.RemoveAllListeners();
        button2.onClick.RemoveAllListeners();
        button3.onClick.RemoveAllListeners();
    }
}

这篇关于检查是否在特定的UI元素上单击了鼠标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆