UI rect touch is not working?

  1. I create a new project
  2. I create a canvas
  3. I create a panel
  4. I change the panel rect transform in the inspector to stretch

So, it looks like image 1.


Then I add this code to the UI panel.

private bool checkFirstTouch = true;

void OnEnable()
	checkFirstTouch = true;


void Update () {
	if (checkFirstTouch) {
		if (Input.GetMouseButton (0)) {	
			foreach (Touch touch in Input.touches) {
				if (gameObject.GetComponent<RectTransform>().rect.Contains(touch.position)) {
					print ("Touched.");
					checkFirstTouch = false;


My problem here is, that when I touch the screen on my mobile device, it’s only working when I touch the left bottom corner. Please look image 2.


Why the whole screen is not working? Because the panel is stretched?

Must I multiply it with canvas scaler or what?

My canvas looks like this:

[Canvas]: Screen Space Overlay


UI Scale Mode: Scale with Screen Size

Reference Resolution: X: 800, Y: 480

Screen Match Mode: Match Width Or Height

Match: 0.5

I’m using Unity 4.7.0.


If I print “gameObject.GetComponent ().rect”, I get this:

(x:-400.00, y:-240.00, width:800.00, height:480.00)

Well, you answered yourself (8
You have a (x:-400.00, y:-240.00, width:800.00, height:480.00) rect and you are trying to test a point which is inside a screen rect (x:0, y:0, width:800.00, height:480.00).
These 2 rects intersect exactly where you drew green rectangle on image 2.

I think you need either change your code to
gameObject.GetComponent<RectTransform>().rect.Contains(touch.position - new Vector2(Screen.width/2, Screen.height/2))
or move pivot on your panel so it would be in the corner.

Of course you also want to cache gameObject.GetComponent<RectTransform>() and new Vector2(Screen.width/2, Screen.height/2) in a variable.