How to select 2D objects using mouse in Unity?

 

Script:

 
    public Camera mainCamera;
    public Vector2 detectionBoxSize = new Vector2(0.2f, 0.2f);
    public float rotationAngle = 0;

    private void Update()
    {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = mainCamera.nearClipPlane;
        Vector2 mouseWorldPosition = mainCamera.ScreenToWorldPoint(mousePosition);

        Collider2D detectedCollider = 
            Physics2D.OverlapBox(mouseWorldPosition, detectionBoxSize, rotationAngle);
    }

How it works:

 

First we need to grab the mouse position using old system it is Input.MousePosition or if you prefere the new input system if could be Mouse.current.position.ReadValue().

In case we are clipping some stuff in our 3d game we want to set the z position to the mainCamera.NearClipPlane but its more useful for 3d games. Still its a good practice to set it.

OverlapBox method simply checks if there is a collider overlapping the box that we create:

We pass in:

  1. The center of the box - we want the mouse position.

  2. Size of the box - in our case it is Vector2(0.2f, 0.2f)

  3. Angel - not sure why but its necessary so I usually pass 0

We can optionally pass a LayerMask to limit the detectable colliders number.

 
 

Want to learn more about Unity ?

Check out my OOP for Unity Devs video course!

 
 

You can also support me through Patreon:

 

If you agree or disagree let me know by joining the Sunny Valley Studio discord channel :)

Thanks for reading!

Peter

Previous
Previous

How to highlight a 3D object in Unity?

Next
Next

How to take a screenshot in Unity?