RaycastHit collider is always null

I’m running this code to detect when player clicks on certain areas on the screen.

private void Update()
	{
		if(Input.GetMouseButtonDown(0))
		{
			var worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
			var hit = Physics2D.Raycast(worldPoint, Vector2.zero);

			print(hit.collider == null ? "no object hit" : hit.collider.name);
		}
	}

The areas have an Image component a a PolygonColldier2D attached. However the code always prints “no bject hit” no matter where I click. What am I missing?

You need to point your ray in the direction you want it to point. It wont it anything if hit is not pointed in any direction/ has no length.


see:

direction A vector representing the
direction of the ray.