Selecting Units within GUI.Box

So, I’ve got a script that creates a GUI.Box when I drag the Mouse.
Although, I’m trying to figure out how to select all of the units inside of that GUI.Box, and I’m having a problem figuring it out.

I know this has been asked before, but the answers just didn’t really explain it for me.

Here’s the code.

using UnityEngine;
using System.Collections;

public class SelectionTool : MonoBehaviour {
	Vector2 lmbDown;
	Vector2 lmbUp;
	bool 	lmbDrag;
	float raycastLength = 200f;
	// Use this for initialization
	void Start () {
	// Update is called once per frame
	void Update () {
		if(Input.GetButtonDown ("Fire1")) {
			lmbDown = Input.mousePosition;
		if(Input.GetButtonUp ("Fire1")) {
			lmbUp = Input.mousePosition;
			lmbDrag = false;
		if(Input.GetButton("Fire1")) {
			selectionBox (Input.mousePosition);
	void selectionBox(Vector2 screenPosition ) {
	    if (screenPosition != lmbDown) {
	        lmbDrag = true;
	        lmbUp = screenPosition;  
	void OnGUI() {
	    if (lmbDrag) {
	        float width = lmbUp.x - lmbDown.x;
	        float height = (Screen.height - lmbUp.y) - (Screen.height - lmbDown.y);
	        Rect rect = new Rect(lmbDown.x, Screen.height - lmbDown.y, width, height);
			GUI.Box (rect, "");

What are your “units” ? Other GUI elements ? GameObjects from your scene “behind” the GUI layer ? Something else ?

In the former case I would recommend to compute whever there is an intersection between your selection rectangle and the bounding rectangles of any other GUI element.

In the latter case, you need a way to determine whever your game objects are included in the frustum of world space that projects to your 2D rectangle in screen space. In other “words”, with a schematic, you want to find the red units and therefore you need to compute which units are in the red frustum :

There is no unique answer to this question, it all depends on the assumptions that you can make on you scene and the precision you want to achieve. For instance, you will not write the same code if you want that a unit becomes selected when a single pixel of it is in the selection rectangle or if “half of it roughly is inside”. But to make it simple and stupid in the second case, I think I’d project every unit’s transform position on the screen plane, then check whether the projected position lies in my selection rectangle.

EDIT : getyour411 suggested exactly the same thing in his comment to the original post while I was writing mine, the linked page contains a relevant code snippet.