Search code examples
c#unity-game-engineclickraycasting

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.


Solution

  • Credit to Juan Bayona Beriso I was missing an Event System Component.