EDIT: I might as well add a method that checks if the unit is in the viewport bounds and a utility method that calculate the bounds. Just so you why I am worried about performance.
Checking if bounds contain unit:
public bool IsWithinSelectionBounds( GameObject gameObject )
{
if (!isSelecting) {
return false;
}
var camera = Camera.main;
var viewportBounds = Utilities.GetViewportBounds( camera, point1, point2);
return viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position));
}
Static utilities:
public static Bounds GetViewportBounds( Camera camera, Vector2 screenPosition1, Vector2 screenPosition2 )
{
var cam = Camera.main;
var v1 = cam.ScreenToViewportPoint( screenPosition1 );
var v2 = cam.ScreenToViewportPoint( screenPosition2 );
var min = Vector3.Min( v1, v2 );
var max = Vector3.Max( v1, v2 );
min.z = camera.nearClipPlane;
max.z = camera.farClipPlane;
var bounds = new Bounds();
bounds.SetMinMax( min, max );
return bounds;
}