Search code examples
c#unity-game-enginetagsraycasting

Is there a way to only acces one collider when there are many colliders with the same tag?


I have a script that moves the object you're touching to the position of your finger, it's based on a tag so when I touch an object with the tag all the objects with the same tag move to that position. Is there a way to make only the one I'm touching move?

The Script

 {
     void FixedUpdate()
     {
         if (Input.touchCount > 0)
         {            
             RaycastHit2D hitInformation = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position),Camera.main.transform.forward);            
                 if (hitInformation.collider.gameObject.tag == "RocketPrefab")
                 {                    
                     Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                     touchPosition.z = -4;
                     transform.position = touchPosition;
                     Debug.Log(touchPosition);

                 }                            
         }
     }
 } ```


Solution

  • You can access the object your Raycast is touching with hitInformation.collider.gameObject.

    From the code that I'm seeing, I think this should work:

         void FixedUpdate()
         {
             if (Input.touchCount > 0)
             {            
                 RaycastHit2D hitInformation = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position),Camera.main.transform.forward);            
                     if (hitInformation.collider.gameObject.tag == "RocketPrefab")
                     {                    
                         Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                         touchPosition.z = -4;
                         hitInformation.collider.gameObject.transform.position = touchPosition;
                         Debug.Log(touchPosition);
                     }                            
             }
         }