Daniel Fox
Daniel Fox

Reputation: 1

Unity2D objects, click on specific object to destroy

I have been looking around and I cannot seem to get this working not matter how I do it. I need to basically remove health for a gameObject by clicking on that object but I can't get it to register that I can clicking on it, here is my code;

if (Input.GetMouseButtonDown(0)) {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
            if (hit.collider.tag == "Player")
        {
                Debug.Log ("Hit " + hit.collider.tag);
        }
    }

Sorry if this is a repeat question, I just really need help with this! (The Debug.Log is just their to show that I am actually hitting the object if it was to work)

Upvotes: 0

Views: 320

Answers (2)

David
David

Reputation: 10708

As mentioned, 2d colliders don't work with 3d raycasting.

2D colliders have also traditionally not supported all the same functions as 3d, and often have issues even trying - it is for this reason that many say you should just use 3d colliders for everything, and lock them into position (usually z = 0) using a script. This is so common practice, that even Unity 5's RigidBody supports a "lock dimension" parameter to keep objects from moving in regards to certain dimensions (usually Z).

Upvotes: 0

Agumander
Agumander

Reputation: 686

3D Raycast doesn't work against 2D colliders. As Salvon suggested, you can use the OnMouseDown() function in the clickable objects.

You can also use Physics2D.OverlapPoint() to "cast" against your 2D objects. You can use the XY portion of the camera's ScreenToWorldPoint() function for this method.

Upvotes: 1

Related Questions