I found some code that generates a selection box, but when I tried it the box was not starting where the mouse was and I couldn't find the issue.
using UnityEngine; public class GUISelectionBox : MonoBehaviour { // Draggable inspector reference to the Image GameObject's RectTransform. public RectTransform selectionBox; // Draggable inspector reference to the scene's rendering camera public Camera currentCamera; // This variable will store the world space position of wherever we first click before dragging. private Vector3 initialClickPosition = Vector3.zero; void Update() { // Click somewhere in the Game View. if (Input.GetMouseButtonDown(1)) { // Get the initial click position of the mouse and transform it to world space, since screen space may change // z-coord is random and irrelevant, we just want a world space position initialClickPosition = currentCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f)); } // While we are dragging. if (Input.GetMouseButton(1)) { // Store the current mouse position in screen space. Vector2 currentMousePosition = new(Input.mousePosition.x, Input.mousePosition.y); // transform initial position to current screen space Vector3 initBoxPosScreenSpace = currentCamera.WorldToScreenPoint(initialClickPosition); // calculate width and height of rect transform float width = currentMousePosition.x - initBoxPosScreenSpace.x; float height = currentMousePosition.y - initBoxPosScreenSpace.y; // set rect's pivot and size selectionBox.anchoredPosition = (Vector2)initBoxPosScreenSpace + new Vector2(width / 2, height / 2); selectionBox.sizeDelta = new Vector2(Mathf.Abs(width), Mathf.Abs(height)); } // After we release the mouse button. if (Input.GetMouseButtonUp(1)) { // Reset initialClickPosition = Vector3.zero; selectionBox.sizeDelta = Vector2.zero; } } } as for the inspector, I have the selection box as an image within a canvas everything was left default and I assigned the correct camera to it.
