I have a scene with a bunch of 2D doors that have 2d Box Colliders (no trigger) on them and that live on a Canvas. I would like to be able to click on them with the mouse, but have had no luck.
Following this earlier topic: (2D) Detect mouse click on object with no script attached , I did the following:
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
if (hit)
{
Debug.Log(hit.collider.gameObject.name);
}
}
However, (hit) is always null. I have no RigidBody2D objects in my scene, because I only need mouse selection, not any interaction between objects.
In the inspector I the green box collider but clicking within it in the scene (not the inspector, obviously) runs the MouseButtonDown() code but still no Raycast hit.
What else could I be missing?
To reduce this to its simplest, you can do the following:
- Create a new 2D scene with a canvas
- Add two 100x100 Images to the Canvas
- Add a Boxcolllider2D to each image
- Now what script is required to detect mouse clicks within them?