Detecting Pointer on UI Object 2D
Hi there, 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.
Is the UI element a child of the canvas? If it is and this script is on the image object, I'm not sure why it's not working. I just quickly tested it and it works for me. You shouldn't need to have a Collider 2D
Answer by IgorAherne · Feb 19, 2017 at 12:08 PM
Make sure none of the parents have canvas group which has Interactable
unticked
If there is such a canvas group, then make sure Block Raycasts is also on.
stick an image on your UI element, make sure it has Raycast Target
ticked on, make its alpha color zero and see if it works
Your answer
Follow this Question
Related Questions
OnCollisionEnter2D issues in Unity 5.2 1 Answer
2D Collision 0 Answers
Collision between two 2D objects. 1 Answer
Compatible collision constraint methods 0 Answers
2d collision detection not working 1 Answer