6
\$\begingroup\$

I'm having a hell of time getting a 2D polygon collider to register a mouse click. I've attached images and code to show where I'm at. I cannot get the click to work.

Ultimately, the thing I'm trying to achieve is to just set the area defined by the collider to be clickable rather than the entire image sprite.

What am I doing wrong here? Need help!

I've defined the collider: I've defined the collider

I've setup the components for my image: I've setup the components for my image

using UnityEngine;
using System.Collections;

public class MouseClick : MonoBehaviour
{
    void OnMouseDown()
    {
        Debug.Log ("Clicked the Collider!");
    }
}
\$\endgroup\$
1
\$\begingroup\$

As already stated you should move to physics raycasts as they allow for greater debugging with on click events.

Your problem with the raycast is mixing Unity's 2DPhysics with 3DPhysics calls.

If you want to Raycast to an object with 2D physics components you must use. Physics2D.Raycast.

The code below should help you find what is obscuring your collider. Attach to any object and use left click.

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(mouseWorldPos, Vector2.zero);
        if(hit != null){
            Debug.Log("Hit Collider: " + hit.transform.name);
        }
        else {
            Debug.Log("No colliders hit from mouse click");
        }
    }
}
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

You can use a RayCast:

     Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
     RaycastHit hit;

     if( Physics.Raycast( ray, out hit, 100 ) )
     {
         Debug.Log( hit.transform.gameObject.name );
     }
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I added that to my function, but I'm still getting nothing. \$\endgroup\$ – greyBow Aug 11 '15 at 13:16
  • \$\begingroup\$ @greyBow because this Raycast is 3D physics. The collider you're using is 2D. Cannot mix 2D and 3D as they are completely different implementations. \$\endgroup\$ – SanSolo Nov 12 '15 at 1:44
0
\$\begingroup\$

Attach a button component to your image after create a script with a public function (any name) then attach your script to any game object, add this game object to the button component and call the function.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.