- Home /
 
               Question by 
               anilgautam · Dec 06, 2012 at 05:07 AM · 
                iphonetouchtouchscreen  
              
 
              How can I detect touch on anroid or iphone
I have a game with lots of gameobjects on screen. I need to know how can I detect that which gameobject I touched. Please explain with example
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by DeveshPandey · Dec 06, 2012 at 05:37 AM
 Try this :
 
 
         bool moving = false;
         GameObject go;
 void Update(){
         if(Input.touchCount == 1)
         {    
             // touch on screen
             if(Input.GetTouch(0).phase == TouchPhase.Began)
             {
                 Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
                 RaycastHit hit = new RaycastHit();
                 moving = Physics.Raycast (ray, out hit);
                 if(moving)
                 {
                     go = hit.transform.gameObject;
                     Debug.Log("Touch Detected on : "+go.name);
                 }
 
             }
 
 
             // release touch/dragging
             if((Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled) && go != null)
             {
                 moving = false;
                 Debug.Log("Touch Released from : "+go.name);
             }
         }    
 }
Answer by DaveA · Dec 06, 2012 at 05:19 AM
It's like this:
http://docs.unity3d.com/Documentation/ScriptReference/Input-mousePosition.html
but uses this:
http://docs.unity3d.com/Documentation/ScriptReference/Input-touches.html
but instead of instantiate, you get the object hit:
http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit-collider.html
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                