,Raycasthit2D do not register collider

Hi,

I am trying to write a script where I can see if a certain sprite is clicked on. But it never seems to register when I click on the sprite, because I don’t see the “lets destroy stuff” message in the console. What am I missing?

Some more info: I am using cinemachine, I have the main camera tagged as main camera with perspetive view set. Therefore I use ScreenPointToRay. I have the sprite assigned to the backButton in the editor, with a box collider 2D on it.

void Update () {

	if (Input.GetMouseButtonDown(0))
    {
        RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));

        //Use the RaycastHit2D to determine if anything was hit by the click:
        if (hit && hit.collider != null && hit.collider == backButton)
        {             
                Debug.Log("Lets destroy stuff");
        }
    }
}

@ellenblomw - The problem is with your comparison:

if (hit && hit.collider != null && hit.collider == backButton)

“I have the sprite assigned as a gameObject in the editor with a box collider 2D attached to it.”

 [SerializeField] GameObject backButton;

If backButton is of type Gameobject, it won’t be true ever, as hit.collider, is like name suggest, a collider. So make your field Collider or get the collider in your condition and compare against it otherwise type won’t match.