How can I prevent my raycast from passing through UI?

Hello Unity Community!

I have this piece of code here:

	private void CheckTap(){
		if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began){
			//if(EventSystem.current.IsPointerOverGameObject()){	
				RaycastHit h;
				Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
				if(Physics.Raycast(ray,out h,15.0f,lmask)){
					if(h.transform.gameObject.tag=="Square") {
						h.transform.gameObject.GetComponent<script_SquareHub>().OnHit();
					}
					else if(h.transform.gameObject.tag=="Bumper"){
						bumperHit.Play();
						switch(livesRemaining){
						case 3: l3.GetComponent<Image>().color=new Color32(205,191,172,150);
							livesRemaining=2;
							break;
						case 2: l2.GetComponent<Image>().color=new Color32(205,191,172,150);
							livesRemaining=1;
							break;
						case 1: l1.GetComponent<Image>().color=new Color32(205,191,172,150);
							livesRemaining=0;
							break;
						case 0: _timeRemaining=0.0f;
							break;
						}
					}
				}
			//}
		}
	}

It works fine on detecting various objects using touch. However, the ray goes through UI, so when I try to pause my game the ray will hit my “Bumper” and cause the player to lose a life.

How can I prevent my ray from passing through the UI? As you can see I’ve tried using IsPointerOverGameObject, but to no success, and setting the layer mask lmask to include UI doesn’t yield the results that I want. Any solution to this?

You had it going well but were missing one extra info.

private int fingerID = -1;
private void Awake()
{
#if !UNITY_EDITOR
    fingerID = 0; 
#endif
}
private void Update()
{
    if (EventSystem.current.IsPointerOverGameObject(fingerID))	// is the touch on the GUI
    {
       // GUI Action
       return;
    }
    // Your raycast code
}

The problem is in editor the parameter for the IsPointerOverGameObject needs to be -1.

Physics raycast doesnt work on new UI I do believe.

You need a Graphic Raycaster

http://docs.unity3d.com/Manual/script-GraphicRaycaster.html

This may also help