Unity UI Events not working for Canvas objects
I'm trying to use the Unity EventSystem to handle certain parts of my interface without having to go through the EventTrigger class.
I've used the EventSystem to select items in my scene in a previous version of my code, but I wanted to take it to the next level and also do things in my interface. At the moment, I want to get edge-scrolling to work. To do that, I have a GameObjects that started out life as a Panel with the UI Sprite removed. It's orientated to the left of the screen, a child of a child of Canvas (and it's parent is full screen).
Attached to that object is this bit of code:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class EdgeScroll : MonoBehaviour,
IPointerEnterHandler,
IPointerExitHandler
{
public enum ScrollDirection
{
Up,
Down,
Right,
Left,
}
public ScrollDirection scrollDirection;
public InterfaceManager IM;
public void OnPointerEnter( PointerEventData eventData )
{
Debug.Log ("EdgeScroll: On Pointer Enter");
switch ( scrollDirection ) {
case ScrollDirection.Up:
IM.scrollVertical = 1f;
break;
case ScrollDirection.Down:
IM.scrollVertical = -1f;
break;
case ScrollDirection.Right:
IM.scrollHorizontal = 1f;
break;
case ScrollDirection.Left:
IM.scrollHorizontal = -1f;
break;
default:
break;
}
}
public void OnPointerEnter( BaseEventData BED)
{
OnPointerEnter (BED as PointerEventData);
}
public void OnPointerExit( PointerEventData eventData )
{
if (scrollDirection == ScrollDirection.Up || scrollDirection == ScrollDirection.Down)
IM.scrollVertical = 0f;
else
IM.scrollHorizontal = 0f;
}
}
It doesn't work. Neither has duplicating the function and putting it through an EventTrigger instead (that's what the second version is). I don't get a call and I don't get any debug printed.Contrast this to 3D objects, for which I have managed a simple EventTrigger.
I'm trying to work out what I'm doing wrong and have looked at the Unity.UI source code, but I can't spot anything I'm not doing that something else (e.g. Button) is. I'm stumped and any help would be appreciated.
Answer by aphenine · Nov 06, 2016 at 08:56 PM
I solved this for myself.
I went back to Panel and tried adding an image, on the off-chance it would work. Lo and behold, it did, especially once I noticed the "Raycast Target" option. This then allowed me to type the right question into a search engine and it turns out my question has already been answered:
http://answers.unity3d.com/questions/1091618/ui-panel-without-image-component-as-raycast-target.html
(Short answer: The Graphics Raycaster in Canvas works only on GameObjects that have a component descended from the Graphics class (e.g. Image). As a result, all UI GameObjects won't intercept events unless they have some kind of Graphic attached.)