# Select box-shape grid between two positions on tilemap

I want to be able to click and hold on a certain point and mark it as startPosition. Then, while the mouse is held down and moved, mark that second position as endPosition.

When the mouse is finally released, I want to get all the positions between those two points.

Here is my code so far:

for (float x = startPosition.x; x <= endPosition.x; x++)
{
for (float y = startPosition.y; y <= endPosition.y; y++)
{
Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
}
}


This works only when dragging up and/or to the right. As soon as I try to go to left or bottom, the endPosition coordinates become smaller than the startPosition coordinates, which breaks the for loop.

How can I solve this?

Solved like this:

        Vector3 lowerLeftTile = new Vector3(Mathf.Min(startPosition.x, endPosition.x), Mathf.Min(startPosition.y, endPosition.y));
Vector3 upperRightTile = new Vector3(Mathf.Max(startPosition.x, endPosition.x), Mathf.Max(startPosition.y, endPosition.y));

for (float x = lowerLeftTile.x; x <= upperRightTile.x; x++)
{
for (float y = lowerLeftTile.y; y <= upperRightTile.y; y++)
{
Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));