简体   繁体   English

在 Unity C# 中获取 2D UI 元素上的 PointerDown

[英]Get PointerDown on 2D UI Element in Unity C#

I've been through number of answers on this topic, but nothing has seemed to work for my case.我已经阅读了有关此主题的许多答案,但似乎对我的情况没有任何帮助。 I'm trying to detect a mouseDown on a UI element with a canvas renderer which is inside the hierarchy of an object with the canvas on it.我正在尝试使用画布渲染器检测 UI 元素上的 mouseDown,该渲染器位于带有画布的对象的层次结构内。 I'm new to this, so I'm not sure if the canvas needs to be linked to this canvas renderer or if they have to be on the same object, but the following code is not resulting in the OnPointerDown method being activated.我是新手,所以我不确定画布是否需要链接到此画布渲染器,或者它们是否必须位于同一个对象上,但以下代码不会导致 OnPointerDown 方法被激活。

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class Knob : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {

    public Slider slider;
    public GameObject pivot;

    public bool selected;
    public float z;
    public Image image;
    public UtilityClass the;
    public float min;
    public float max;

    void Start () {
        z = 90;

        Quaternion rotation = Quaternion.Euler (0, 0, z);
        pivot.transform.rotation = rotation;
    }


    void Update() {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

        if (selected) {

            float pivotAngle = the.AngleFrom (the.Heading (pivot.transform.position, mousePosition));
            if (pivotAngle >= min && pivotAngle <= max)
                z = pivotAngle;

            Quaternion rotation = Quaternion.Euler (0, 0, z);
            pivot.transform.rotation = rotation;
        }
    }

    public void OnPointerDown(PointerEventData eventData) {
        selected = true;
    }

    public void OnPointerUp(PointerEventData eventData) {
        selected = false;
    }
}

At the moment I don't have a Collider 2D on the object, but I have "Raycast Target" selected in the Image script.目前我在对象上没有 Collider 2D,但我在图像脚本中选择了“Raycast Target”。 Any help would be appreciated.任何帮助,将不胜感激。

感谢 Juan Bayona Beriso 我缺少一个事件系统组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM