如何检测 UI 和游戏对象上的点击/触摸事件 [英] How to detect click/touch events on UI and GameObjects

查看:25
本文介绍了如何检测 UI 和游戏对象上的点击/触摸事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 android 中的 Canvas on Touch 上检测 UI 对象?

How to detect UI object on Canvas on Touch in android?

例如,我有一个画布,其中有 5 个对象,例如 ImageRawImageButtonsInputField 等等.

For example, I have a canvas that have 5 objects such as Image, RawImage, Buttons, InputField and so on.

当我触摸 Button UI 对象时,然后做一些事情.每个按钮在点击时执行不同的处理.

When I touch on Button UI object Then do something. Each button do different process when clicked depending.

代码如下:

private void Update()
{
    if (Input.touches.Length <= 0) return;

    for (int i = 0; i < Input.touchCount; i++)
    {
        if (Button1.touch)
            if (Input.GetTouch(i).phase == TouchPhase.Began)
                login();
        else if (Button2.touch && Input.GetTouch(i).phase == TouchPhase.Began)
            LogOut();
    }
}

那怎么办呢?

第二:如何检测 Gameobject 得到触摸?和上面的一样吗?

Second: How to detect Gameobject get touch? Is it same with that above or not?

推荐答案

您没有将 Input API 用于新 UI.您可以根据事件订阅 UI 事件或实现接口.

You don't use the Input API for the new UI. You subscribe to UI events or implement interface depending on the event.

这些是在新 UI 组件上检测事件的正确方法:

These are the proper ways to detect events on the new UI components:

1.图片RawImageText 组件:

实现所需的接口并覆盖其功能.下面的示例实现了最常用的事件.

Implement the needed interface and override its function. The example below implements the most used events.

using UnityEngine.EventSystems;

public class ClickDetector : MonoBehaviour, IPointerDownHandler, IPointerClickHandler,
    IPointerUpHandler, IPointerExitHandler, IPointerEnterHandler,
    IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("Drag Begin");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("Dragging");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("Drag Ended");
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Mouse Down: " + eventData.pointerCurrentRaycast.gameObject.name);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Mouse Enter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Mouse Exit");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("Mouse Up");
    }
}

2.按钮 组件:

您使用事件注册按钮点击:

You use events to register to Button clicks:

public class ButtonClickDetector : 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
            Debug.Log("Clicked: " + button1.name);
        }

        if (buttonPressed == button2)
        {
            //Your code for button 2
            Debug.Log("Clicked: " + button2.name);
        }

        if (buttonPressed == button3)
        {
            //Your code for button 3
            Debug.Log("Clicked: " + button3.name);
        }
    }

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

如果您检测到的不是 Button Click 按钮,则使用方法 1.例如,Button down 而不是 Button Click,使用 IPointerDownHandler 及其 OnPointerDown 函数来自方法 1.

If you are detecting something other than Button Click on the Button then use method 1. For example, Button down and not Button Click, use IPointerDownHandler and its OnPointerDown function from method 1.

3.InputField 组件:

您使用事件注册来注册 InputField 提交:

You use events to register to register for InputField submit:

public InputField inputField;

void OnEnable()
{
    //Register InputField Events
    inputField.onEndEdit.AddListener(delegate { inputEndEdit(); });
    inputField.onValueChanged.AddListener(delegate { inputValueChanged(); });
}

//Called when Input is submitted
private void inputEndEdit()
{
    Debug.Log("Input Submitted");
}

//Called when Input changes
private void inputValueChanged()
{
    Debug.Log("Input Changed");
}

void OnDisable()
{
    //Un-Register InputField Events
    inputField.onEndEdit.RemoveAllListeners();
    inputField.onValueChanged.RemoveAllListeners();
}

4.滑块 组件:

要检测拖动期间滑块值何时发生变化:

To detect when slider value changes during drag:

public Slider slider;

void OnEnable()
{
    //Subscribe to the Slider Click event
    slider.onValueChanged.AddListener(delegate { sliderCallBack(slider.value); });
}

//Will be called when Slider changes
void sliderCallBack(float value)
{
    Debug.Log("Slider Changed: " + value);
}

void OnDisable()
{
    //Un-Subscribe To Slider Event
    slider.onValueChanged.RemoveListener(delegate { sliderCallBack(slider.value); });
}

对于其他事件,请使用方法 1.

For other events, use Method 1.

5.下拉 组件

public Dropdown dropdown;
void OnEnable()
{
    //Register to onValueChanged Events

    //Callback with parameter
    dropdown.onValueChanged.AddListener(delegate { callBack(); });

    //Callback without parameter
    dropdown.onValueChanged.AddListener(callBackWithParameter);
}

void OnDisable()
{
    //Un-Register from onValueChanged Events
    dropdown.onValueChanged.RemoveAllListeners();
}

void callBack()
{

}

void callBackWithParameter(int value)
{

}

<小时>

非用户界面对象:

6.对于 3D 对象(网格渲染器/任何 3D 碰撞器)

6.For 3D Object (Mesh Renderer/any 3D Collider)

PhysicsRaycaster 添加到相机,然后使用方法 1 中的任何事件.

Add PhysicsRaycaster to the Camera then use any of the events from Method 1.

下面的代码会自动将PhysicsRaycaster添加到主Camera.

The code below will automatically add PhysicsRaycaster to the main Camera.

public class MeshDetector : MonoBehaviour, IPointerDownHandler
{
    void Start()
    {
        addPhysicsRaycaster();
    }

    void addPhysicsRaycaster()
    {
        PhysicsRaycaster physicsRaycaster = GameObject.FindObjectOfType<PhysicsRaycaster>();
        if (physicsRaycaster == null)
        {
            Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
    }

    //Implement Other Events from Method 1
}

7.对于 2D 对象(Sprite Renderer/任何 2D Collider)

7.For 2D Object (Sprite Renderer/any 2D Collider)

Physics2DRaycaster 添加到相机,然后使用方法 1 中的任何事件.

Add Physics2DRaycaster to the Camera then use any of the events from Method 1.

下面的代码会自动将Physics2DRaycaster添加到主Camera.

The code below will automatically add Physics2DRaycaster to the main Camera.

public class SpriteDetector : MonoBehaviour, IPointerDownHandler
{
    void Start()
    {
        addPhysics2DRaycaster();
    }

    void addPhysics2DRaycaster()
    {
        Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
        if (physicsRaycaster == null)
        {
            Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
    }

    //Implement Other Events from Method 1
}

<小时>

对事件系统进行故障排除:

在 UI、2D 对象(精灵渲染器/任何 2D 碰撞器)和 3D 对象(网格渲染器/任何 3D 碰撞器)上未检测到点击:


Troubleshooting the EventSystem:

No clicks detected on UI, 2D Objects (Sprite Renderer/any 2D Collider) and 3D Objects (Mesh Renderer/any 3D Collider):

A.检查您是否有 EventSystem.如果没有 EventSystem,它根本无法检测到点击.如果您没有,请自行创建.

A.Check that you have EventSystem. Without EventSystem it can't detect clicks at-all. If you don't have have it, create it yourself.

转到GameObject ---> UI ---> 事件系统.如果尚不存在,这将创建一个 EventSystem.如果它已经存在,Unity 将忽略它.

Go to GameObject ---> UI ---> Event System. This will create an EventSystem if it doesn't exist yet. If it already exist, Unity will just ignore it.

B.UI 组件或带有 UI 组件的 GameObject 必须在 Canvas 下.这意味着 Canvas 必须是 UI 组件的父级.没有这个,EventSystem 将无法运行,也不会检测到点击.

B.The UI component or GameObject with the UI component must be under a Canvas. It means that a Canvas must be the parent of the UI component. Without this, EventSystem will not function and clicks will not be detected.

这仅适用于 UI 对象.它适用于 2D(精灵渲染器/任何 2D 碰撞器)或 3D 对象(网格渲染器/任何 3D 碰撞器).

This only applies to UI Objects. It doesn't apply to 2D (Sprite Renderer/any 2D Collider) or 3D Objects (Mesh Renderer/any 3D Collider).

C.如果这是一个 3D 对象,PhysicsRaycaster 不会附加到相机.确保 PhysicsRaycaster 已连接到相机.有关详细信息,请参阅上面的 #6.

C.If this is a 3D Object, PhysicsRaycaster is not attached to the camera. Make sure that PhysicsRaycaster is attached to the camera. See #6 above for more information.

D.如果这是一个 2D 对象,Physics2DRaycaster 不会附加到相机.确保 Physics2DRaycaster 已连接到相机.有关详细信息,请参阅上面的 #7.

D.If this is a 2D Object, Physics2DRaycaster is not attached to the camera. Make sure that Physics2DRaycaster is attached to the camera. See #7 above for more information.

E.如果这是一个 UI 对象,您希望使用 OnBeginDragOnPointerClick 等界面功能检测点击>OnPointerEnter#1 中提到的其他函数,然后带有检测代码的脚本必须附加到您想要检测点击的 UI 对象.

E.If this is a UI object you want to detect clicks on with the interface functions such as OnBeginDrag, OnPointerClick, OnPointerEnter and other functions mentioned in #1 then the script with the detection code must be attached to that UI Object you want to detect click on.

F.此外,如果这是您想要检测点击的 UI 对象,请确保它前面没有其他 UI 对象.如果在您要检测点击的 UI 前面有另一个 UI,它将阻止该点击.

F.Also, if this is a UI Object you want to detect clicks on, make sure that no other UI Object is in front of it. If there is another UI in front of the one you want to detect click on, it will be blocking that click.

要验证这不是问题,请禁用 Canvas 下的所有对象,除了要检测的对象单击后,再查看单击是否有效.

To verify that this is not the issue, disable every object under the Canvas except the one you want to detect click on then see if clicking it works.

这篇关于如何检测 UI 和游戏对象上的点击/触摸事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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