- Home /
Destroying object by touch on Android? (JS)
Hey so, let's say I have got 5 cubes with same script attached and with random positions and i want to destroy them (not every at once) while tap on it. I found on google someone talking about Physic.raycast but I don't really understand how does that work :/ It would be awesome if someoce can maybe explain that to me :)
Answer by Joyrider · Aug 16, 2013 at 02:29 PM
Have a look at the scripting reference, it has examples and everything
Basically, your create a ray from you tap's position, in the same direction the camera is facing. And you'll detect if the ray hits any colliders. Which simply means you create a ray under your finger. (For this all your cubes need to have a collider object!).
if he does hit, you can get the RayCastHit data back from the raycast, and access severl types of data from that hit (exact point, object, texture uv,...)
Oh okay I see :) But i'm having weird error... I was trying to use and example from scripting reference:
function Update() {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, 100)) {
print ("Hit something");
}
}
But When I attach it to camera and I run it I have his:
NullReferenceException
UnityEngine.Camera.ScreenPointToRay (Vector3 position) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:376)
Raycast.Update () (at Assets/Scripts/Raycast.js:2)
Should I attach it to another object, or am I doing wrong something else?
Allright i fixed that, i just had to change tag of the camera to $$anonymous$$ainCamera :)
Finally got code working :D Here is it if someone is interesed:
function Update ()
{
if (Input.touchCount > 0)
{
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
{
Debug.Log(" You just hit " + hit.collider.gameObject.name);
if(hit.collider.tag == "Part")
{
Destroy(hit.transform.gameObject);
}
}
}
}
touches works perfect) *ps. I used it for my mobile UI, as I know standart OnGUI is bad for mobiles.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112336im_/https://answers.unity.com/themes/thub/images/avi.jpg)