touch in unity code example

Example 1: touch gameobject in unity

using UnityEngine; using System.Collections;  public class RaycastTest : MonoBehaviour {      Vector3 touchPosWorld;      //Change me to change the touch phase used.     TouchPhase touchPhase = TouchPhase.Ended;      void Update() {         //We check if we have more than one touch happening.         //We also check if the first touches phase is Ended (that the finger was lifted)         if (Input.touchCount > 0 && Input.GetTouch(0).phase == touchPhase) {             //We transform the touch position into word space from screen space and store it.             touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);              Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);              //We now raycast with this information. If we have hit something we can process it.             RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);              if (hitInformation.collider != null) {                 //We should have hit something with a 2D Physics collider!                 GameObject touchedObject = hitInformation.transform.gameObject;                 //touchedObject should be the object someone touched.                 Debug.Log("Touched " + touchedObject.transform.name);             }         }     } }

Example 2: unity mobile touch input

// its a simple jump on tap and while tap controller
// for a geometry dash like game
void MobileController(){
        // for the touch movement
        if (Input.touchCount > 0)
        {
	        theTouch = Input.GetTouch(0);

	        if ((theTouch.phase == TouchPhase.Began || theTouch.phase == TouchPhase.Stationary 
            || theTouch.phase == TouchPhase.Moved) && isGrounded)
        	{
	        	myRigidbody.AddForce(Vector3.up * (jumpPower * myRigidbody.mass * myRigidbody.gravityScale * 10.0f));
                myAudioPlayer.PlayOneShot(jump);
                isGrounded = false;
        	}
        }
    }