Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Making an RTS selection box

Discussion in 'Scripting' started by krarkrrrc, Dec 13, 2015.

  1. krarkrrrc

    krarkrrrc

    Joined:
    Oct 22, 2015
    Posts:
    2
    I'm trying to draw a rectangle on the screen when the player left clicks and drags. This code detects the left click but freezes when it enters the while loop:

    if (Input.GetMouseButtonDown(0))
    {
    Debug.Log("clicked the left mouse button");
    startClick = Input.mousePosition;
    while (Input.GetMouseButtonDown(0))
    {
    selectionBox = new Rect(startClick.x, startClick.y, startClick.x + 100, startClick.y + 100);
    Graphics.DrawTexture(selectionBox, selectionTexture);
    }


    }
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Input is only updated once per frame. So you have created an infinite loop.

    You could make it a coroutine. Or you could set a bool that you clear when the mouse is released and change your while to an if.
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    GetMouseButtonDown - the first frame when the mouse button is pressed (setup and create the rect)
    GetMouseButton - every frame where the mouse button is held down (update the rect, i.e. where you should be doing what you are trying to use a while for, DONT use a while, it updates every frame and you don't want to work within a frame, but over all the frames the user holds down the button).
    GetMouseButtonUp - the frame when the mouse button is released (remove rect, hand selection stuff etc.)

    there are probably better approaches, but this appears to be what you were attempting, just needs the start, middle, end. not the start, start, start, start, start... ad infinitum
     
    Kiwasi likes this.
  4. Sose

    Sose

    Joined:
    Dec 10, 2015
    Posts:
    27
    Code (csharp):
    1.  
    2. private Vector3 firstClick;
    3. private bool selecting = false;
    4.  
    5. void Update () {
    6.   if (Input.GetMouseButtonDown(0))
    7.   {
    8.     firstClick = MousePosInWorld();
    9.     selecting = true;
    10.   }
    11.  
    12.   if (Input.GetMouseButtonUp(0))
    13.   {
    14.     selecting = false;
    15.   }
    16.  
    17.   if (selecting)
    18.   {
    19.     Debug.DrawLine(firstClick, MousePosInWorld());
    20.   }
    21. }
    22.  
    23. Vector3 MousePosInWorld()
    24. {
    25.   return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    26. }
    27.  
     
    Kiwasi likes this.