简体   繁体   中英

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

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. Any help would be appreciated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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