Touch Input on Multiple objects in Grid.

Hi Community,

I am from flash background and new to Unity 2D. While exploring the touch inputs in unity2D I faced a problem in getting reference to the object which is touched. I created a TouchInput2D script and attached the same to the two sprite objects in the grid. Box Collider 2D component is added to both the sprite objects. While touching those objects I want to get "name" of the object which is touched.

Following is my implementation:

void Update () 
{
     for (int i = 0; i < Input.touchCount; i++)
     {
          Touch touch = Input.GetTouch(i);

          Vector3 pos = Camera.main.ScreenToWorldPoint (new Vector3(touch.position.x, touch.position.y, 0));

          if (Physics2D.Raycast(pos,Vector2.zero))
          {
                if(touch.phase == TouchPhase.Began)
                {
                     Debug.Log("Touch Begun on: " + this.name);
                }
                if(touch.phase == TouchPhase.Ended)
                {
                     Debug.Log("Touch Ended on: " + this.name);
                }
          }
     }
}

Name of the items are : "item1" and "item2". The PROBLEM is that even if touch item1 then in the console it gives me touch input for both the items(item1 and item2), means console outputs the name of both the items even If I tap on just one of it.

Thanks in advance.

Firstly, please use Code Tags when posting code snippets.
Everything else causes our brains to melt and the motivation to help converges to zero.

I assume to know what you tried to achieve but that doesn't work this way. The issue is that you attached the script to both of your game objects. Now both game objects perform a hit detection and when you actually hit something, both game objects will print their own name. At least that's what I got from your code and description.

Physics2D.Raycast returns a RaycastHit2D. To make your code work, attach the script to e.g. an empty game object (just to have a logical separation from your item objects). Then, if you hit something (which means that the returned instance of RaycastHit2D is not null), you can print the collider's name (RaycastHit2D.collider) to the console.

1 Like

Hey Bivrost,

Apologies for the code tags while pasting the snippet. Actually I thought that it will maintain the tabs automatically. Will be more careful next time onwards.

I tried your approach and attached the script to the empty game object and got the desired results. The main problem was that I attached the script to both the objects like we add an Event Listener in flash individually for each and every object. Now finally the problem is resolved.

Thanks a bunch.

Thank you so much
Your response is a lifesaver

Please use the like button to show your appreciation instead of reviving a 10-year-old thread ;)+
Thread locked

1 Like