Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2D Marquee selection with BoxCastAll? [For top-down RTS]

Discussion in '2D' started by Gibbons, Jun 1, 2014.

  1. Gibbons

    Gibbons

    Joined:
    Feb 28, 2013
    Posts:
    8
    Hi guys,

    I'm fairly new to both Unity and programming, and I've started work on a small RTS game. Currently I've made sprites highlightable when the user hovers their mouse over them, and when selected, they're added to a selection manager list and it toggles a "selected" bool for the individual sprite.

    Code (csharp):
    1.  
    2. void Update ()  
    3.     {
    4.         if (Input.GetButtonDown ("Left Click")) {LeftClick();}
    5.         if (Input.GetButtonDown ("Right Click")){RightClick();}    
    6.     }
    7.  
    8.     void LeftClick()
    9.     {
    10.         RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    11.  
    12.  
    13.         if ((Input.GetKey (KeyCode.LeftShift)   (hit.collider == null))){}//do nothing while holding shift and clicking ground                                                                         
    14.         else if (hit.collider == null)                                      //if player clicks ground, everything deselects
    15.             player.GetComponent<SelectionManager>().selectionList.Clear();  
    16.  
    17.         if ((Input.GetKey (KeyCode.LeftShift))   (hit.collider != null))    //this for shift-click additive selection
    18.         {
    19.             if(hit.collider.GetComponent<UnitInfo>())  
    20.                 hit.collider.GetComponent<UnitInfo>().Clicked();               
    21.         }
    22.         else if(hit.collider != null)                                       //selects a unit and deselects previous selection
    23.         {
    24.             player.GetComponent<SelectionManager>().selectionList.Clear();
    25.             if(hit.collider.GetComponent<UnitInfo>())
    26.                 hit.collider.GetComponent<UnitInfo>().Clicked();
    27.         }
    28.     }
    29.  
    I like to think that I've got all the standard parts of RTS unit selection except for marquee selection. As in dragging a box around a point in the screen and sending information to all the gameobjects within that box when the mouse button is released.

    So the first thing to do is drag-draw a transparent GUI box for visuals, and also draw a BoxCastAll that only "selects" the objects but only when the mouse button is released. Eek.

    I've looked around a lot for a solution, but I've only found those that apply to 3D games. 2D is supposedly much more straightforward, but I still see little information.

    Could anyone please help me out with any suggestions?