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"); } }