如何检测 UI 和 GameObjects 上的点击/触摸事件

How to detect click/touch events on UI and GameObjects(如何检测 UI 和 GameObjects 上的点击/触摸事件)
本文介绍了如何检测 UI 和 GameObjects 上的点击/触摸事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,我有一个包含 5 个对象的画布,例如 Image、RawImageButtonsInputField 等等.

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?

推荐答案

您没有为新 UI 使用 Input API.根据事件订阅 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 上检测到的不是 Button Click,则使用方法 1.例如,Button down 而不是 Button Click,请使用 IPointerDownHandler 及其 OnPointerDown 函数从方法一开始.

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.

5.Dropdown 组件

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)
{

}

<小时>

非 UI 对象:

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 对象(Sprite 渲染器/任何 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(Sprite 渲染器/任何 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对象,你想用OnBeginDragOnPointerClickOnPointerEnter#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,它将阻止该点击.

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 和 GameObjects 上的点击/触摸事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)