Mouse over UI elements won't work

I have a simple script called InputManager and (for now) all it does is just to detect whether the mouse is over UI elements or not, just to prevent unwanted behaviors in the game.

  1. void Update()
  2. {
  3. if (EventSystem.current.IsPointerOverGameObject())
  4. {
  5. Debug.Log("Its over UI elements");
  6. }
  7. else
  8. {
  9. Debug.Log("Its NOT over UI elements");
  10. }
  11. }

The problem is that the message "Its over UI elements" always shows up in the console, I turned off the canvas just to see if there is something messing with this function but nothing happened, apparently a lot of devs are suffering from the same issue.

Can someone tell me what to do?

I hope this will work.

public static bool IsPointerOverUI()
			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;