如何在UI和GameObjects上检测单击/触摸事件 [英] How to detect click/touch events on UI and GameObjects

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

问题描述

如何在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?

推荐答案

对于新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 . Image RawImage

1.Image, RawImage and Text Components:

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

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 . Button 组件:

2.Button Component:

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

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,然后使用方法1.例如,按下Button而不是Button Click,请使用IPointerDownHandler及其方法1中的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 组件:

3.InputField Component:

您使用事件进行注册以注册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 . Slider 组件:

4.Slider Component:

要检测拖动期间滑块值何时改变:

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

}


非用户界面对象:

6 .对于3D对象(Mesh Renderer/任何3D Collider)

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 Renderer/任何2D Collider)和3D对象(Mesh Renderer/任何3D Collider)上均未检测到点击:


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 Renderer/任何2D Collider)或3D Objects(Mesh Renderer/任何3D Collider).

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.

要确认这不是问题,请禁用画布"下的所有对象,但要检测的对象除外,请单击并查看其是否有效.

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上检测单击/触摸事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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