RTS Style square selection for noobs

Hi, I know this question has been asked dozens of times but truth is that for a complete beginner such as myself, there is not really enough conclusive data on how to pull off a simple RTS Style square selection box. I’d like to be assisted with this providing the following scenario:

I already have the mouse’s start position, released position and a list of gameobjects in two vectors (C#):

Vector2 mouseStart; //already assigned in update method onmousedown
Vector2 mouseRelease; //already assigned in update method onmouseup after onmousedown
List<GameObject> selectedUnits = new List<GameObject>();

Now what code would be required during the update function to return each gameobject in that square into the array of gameobjects?

void update(){
//Code to populate SelectedUnits goes here
}

I have done successful raycasts with a single vector3 which is the camera position, and I’ve read about WorldToViewportPoint and ViewportToWorldPoint but that’s where I get stuck. So any code that explains this (if these are the right methods) and successfully populates my arraylist would be much appreciated, thanks.

Here is an outline of what you need to do:

  • First you need to get a list of potential game objects. If they are all tagged the same you can use GameObject.FindGameObjectsWithTag(). Or maybe you maintain a list. An inefficient method is to use Object.FindObjectsOfType().
  • Step 2 is to normalize the selection. The user will be able to select in any direction. I’d look at mouseStart and mouseRelease and initialize four variables minX, minY, maxX and maxY.
  • For each game object in your array of potential objects (step 1), convert the position to screen coordinates. Use Camera.WorldToScreenPoint() to make the conversion.
  • If the position’s x value is between minX and maxX and the position’s y value is between minY and maxY, add it to your list.

Note this method uses the pivot point. That is, it selects anything where the pivot point is within the bounds you set. You may want anything that is even partly contained within the selection, or everything that is entirely within the selection. Both are significantly harder than what I’ve outlined.