Raycasting to find mouseclick on Object in unity 2d games

Bimal Bose B S picture Bimal Bose B S · Dec 14, 2013 · Viewed 41.2k times · Source

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).

Answer

Esa picture Esa · Mar 3, 2014

You cannot use 3D physics functions on the new 2D stuff. Use the 2D functions instead. Example:

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

if(hit.collider != null)
{
    Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
}