0

I am using

void Update()
{`for (var i = 0; i < Input.touchCount; ++i)
    {
        if (Input.GetTouch(i).phase == TouchPhase.Began)
        {

            // Construct a ray from the current touch coordinates
    Ray ray =      Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
             if (Physics.Raycast(ray))
Destroy();
        }
    }

}

I tested on my mobile phone (Windows Phone) to see if I can touch my object to destroy. This script is also attached to the object, so when touched it should get destroyed. Instead, if I touch anywhere in the screen, all the objects, which is multiple duplicates of one object, gets destroyed instead of the specific one I touch. This does not happen when I use OnMouseDown. Is there something I can do similar to MouseDown with touch control?

Manash Yes
  • 15
  • 1
  • 5

2 Answers2

0

Try using

Destroy(gameObject);

Or

Destroy(this.gameObject);
Jpc133
  • 28
  • 1
  • 4
  • That would destroy whatever GameObject this script is attached to, which may or may not be the GameObject the player has just tapped. – rutter Mar 05 '15 at 02:01
  • I don't know why but I assumed the script was attached to the object your destroying. – Jpc133 Mar 05 '15 at 06:17
0

Physics.Raycast returns a boolean that indicates whether or not you hit anything, which is useful, but in this case you also need to know what you hit.

Luckily, there are overrides of the Raycast function that do populate this data, using an out parameter to populate a RaycastHit. If you haven't seen the out keyword in C#, before, it's similar to pass-by-reference in other languages.

If the raycast returns true, then the hit data has been populated and you can find out more about whatever the user just tapped on. For example, which GameObject was it?

Quick example:

RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
    Destroy(hit.collider.gameObject);
}

For more information, including optional arguments to control the raycast or other details you can pull out of the hit data, see the manual pages I linked above.

Community
  • 1
  • 1
rutter
  • 11,242
  • 1
  • 30
  • 46