[Solved] How to detect when you touch a game object

Updated on August 9, 2014 in [A] 2D
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
5 on August 8, 2014

Hello,
I’ve been trying to figure out how to detect when you touch a game object, but I can’t get it working! (in Unity 2D)
I have looked on the Unity Documentation and Unity Answers but nothing seems to be working for me.
All I want is:
If you touch an object then destroy that object.
I’ve been looking at raycasts but not really sure how to write it all out.
I saw this answer on Unity Answers which doesn’t use any raycasts, but that doesn’t seem to work for me.

At the moment I have this:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
 {

But this only tests if I touch the screen, and not on a specific object.

Could someone explain the easiest method of doing this?

EDIT:
I’ve managed to get it working, here’s the code if anyone else has the same problem:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.GetTouch (0).position)), Vector2.zero);
if(hit.collider != null)
{
Debug.Log ("Touched it");
}
}

  • Liked by
  • Zombie Slayer
Reply
0 on August 8, 2014

Hi Daedalus,

You’ll need a collider on the object that you want to destroy and a script on that object.  Check if the object colliding equals the player (or whatever your object that’s doing the touching), then call the Destroy(gameObject).

  • Liked by
Reply
Cancel
0 on August 8, 2014

I have a 2d collider on the object I want to destroy.There isn’t another object that’s colliding with it, it’s when I tap on the object with the touch screen. How would I code this?

  • Liked by
Reply
Cancel
0 on August 8, 2014

This may help some: 
https://www.youtube.com/watch?v=rOq9wwADIHU

This will at least get you able to click with a mouse onto an object to destroy.  I’m not sure how to take inputs from the screen.  I haven’t been coding for mobile apps yet, just PC and haven’t had a chance to look into it.  I remember Pixelnest.io having a touch input tutorial.  You might check that out as wel.

  • Liked by
Reply
Cancel
0 on August 8, 2014

You still need a 2d collider to do this

// This function  take action when the mouse is clickked on the object or is tapped on
OnMouseDown(){
Destroy(gameObject)
} 

hope this helps

  • Liked by
Reply
Cancel
0 on August 9, 2014

I’ve managed to get it working, here’s the code if anyone else has the same problem:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
 {
 RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.GetTouch (0).position)), Vector2.zero);
 if(hit.collider != null)
 {
 Debug.Log ("Touched it");
 }
 }

Thanks for the replies guys

  • Liked by
Reply
Cancel