Touch input not working

I am trying to create a button using a sprite with a box collider 2D attached. I have got it to work without using raycast but it is not very accurate. Now it does not do anything when I press the button.

I have used the documentation to put this together.

	var levelToLoad : String; 
	var newSprite : Sprite;

	
	
function Update ()
{
		for (var i = 0; i < Input.touchCount; ++i) {
			if (Input.GetTouch(i).phase == TouchPhase.Began) {
				// Construct a ray from the current touch coordinates
				var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
				if (Physics.Raycast (ray)) {	
		GetComponent(SpriteRenderer).sprite = newSprite;
		LoadNewLevel();
		Debug.Log("Touched");
			
			}
		}
	}
}
		
function LoadNewLevel()
{
	yield WaitForSeconds(0.5);
	Application.LoadLevel(levelToLoad);
}

Thanks.

In your Physics.Raycast you need to specify the distance for the ray.

Refer: Physics.Raycast

So your if loop becomes

if (Physics.Raycast (ray, 100)) {
  DoSomeStuff();
}

Also if you want to detect the collider which the ray hit you can use:

var hit : RaycastHit;

    if(Physics.Raycast(ray, hit, 100)) {
        print(hit.collider.name);
    }

You are using 2D collider that’s why you have to use “Physics2D.Raycast()”. I hope this would help you…

In the end I had trouble with both answers. Tested and Working now, it was much simpler than I was making it.

Here is the code that will allow a button to change sprite and load the level you want:

	var levelToLoad : String; 
	var newSprite : Sprite;


function Update ()
{
   var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);
   
   if(Input.touchCount > 0)
   {
      if(hit.collider.name == "Button")
      {
     GetComponent(SpriteRenderer).sprite = newSprite;
     LoadNewLevel();
       
      }
	}
}



function LoadNewLevel()
{
	yield WaitForSeconds(0.5);
	Application.LoadLevel(levelToLoad);
}