- Home /
How to prevent touch going through UI?
I have been reading about this problem a lot but it seems I just can't figure this out. The problem is that touch goes through my UI elements and activates buttons behind UI.
I have tried using the event system to prevent this and it works fine with mouse on PC, but when I build the game touches still go through on Android devices.
This is what I've tried:
if(!EventSystem.current.IsPointerOverGameObject ())
{
//Button script here
}
I also tried this without any success:
if(!EventSystem.current.IsPointerOverGameObject (Input.GetTouch (0).fingerId))
{
//Button script here
}
I suspect I need to add something else to the code above to make it work, but what might that be?
I have also tried setting the button gameobjects inactive when the UI layout is activated, but for some weird reason the UI acts like the gameobjects still exist even when they have been set completely inactive. I have no idea how this is even possible...
If someone could explain to me how to fix this it would be really nice.
Answer by christianstrang · Sep 11, 2015 at 12:30 PM
This solution from @Fattie works fine, though you have to do one more thing for this to work on mobile:
Check the inputbox for "Allow Activation On Standalone" on your "EventSystem" object in your canvas object. After that step, it worked fine for me on mobile and desktop.
Answer by JayadevHaddadi · May 03 at 06:38 AM
This fix works from me:
private bool IsPointerOverUIObject() {
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
Got it from: http://answers.unity.com/answers/1115473/view.html