I am trying to delete the object on which the mouse is clicked. I am making a 2D game using the new Unity3D 4.3. Here is the code I'm using
void Update () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit))
{
isHit = false;
Destroy(GameObject.Find(hit.collider.gameObject.name));
}
}
}
The control is not entering the inner if loop. (isHit
is not being set as false).
You've to attach a mesh collider(any collider) with your object first to enter the inner If. Then,
will simply do the job.
There's might be an other work around here.
You cannot use 3D physics functions on the new 2D stuff. Use the 2D functions instead. Example:
This question is a bit old, but I was looking for a a way to get a GameObject with a mouse click in unity 2D, and the Answer from Esa almost helped me, but I couldn't afford to make it to work, so with a bit of research I saw that Camera.main.ScreenToWorldPoint was returning the center of the screen area of the Camera and to it work right. it required to enter the difference in Z position from the camera and the nearest GameObject. My Camera was set by default in -10 and my GameObject was in 0, so all I needed to do is set my Input.mousePosition.z to 10. So if you are getting problem to work with Esa's code (like me :( )the code bellow may help you:
First attach any type of 2D collider to your GameObject, then pick one of those solutions;
1st Case - If there are more than 1 GameObject on top of each other, and you try to understand specific GameObject is clicked:
2nd Case - If there is only 1 GameObject, and you try to understand if it is clicked: