- Home /
Applying a script to multiple gui boxes
Hi, I have written the following script that draws a gui box then allows the user to drag it around the screen. However, I need to be able to add boxes dynamically and be able to drag them all. How would I modify my script to be able to accommodate for multiple boxes?
private var progress: int;
var mySpeed: int;
var pos: Vector2; //position of box
var size: Vector2; // size of box
var within: boolean = false; //checks if clicked inside box
var mousePos: Vector2; // current mouse positon
var xOffset = 0; //used to calculate where in the box user clicked
var yOffset = 0; //used to calculate where in the box user clicked
function OnGUI() {
// Constrain all drawing to be within a pixel area .
GUI.BeginGroup(new Rect(pos.x, pos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), "Hi"); //draw the box everyframe
// Always match BeginGroup calls with an EndGroup call
GUI.EndGroup();
}
function Update() { //within every frame
if (Input.GetMouseButtonDown(0)) //if user presses the left mouse
{
mousePos = Input.mousePosition; //get current position of mouse
mousePos.y = Screen.height - mousePos.y; //used to invert the y value of mousePosition
if (mousePos.x > pos.x && mousePos.x < (pos.x + size.x)) //if user has clicked with the box's X co-ords
{
if (mousePos.y > pos.y && mousePos.y < (pos.y + size.y)) //if user has clicked with the box's Y co-ords
{
within = true; //set within to true to let the script know
xOffset = mousePos.x - pos.x; //set where in teh box the user has clicked
yOffset = mousePos.y - pos.y; //set where in teh box the user has clicked
}
}
}
if (Input.GetMouseButton(0)) //if left mouse button is held down
{
if (within == true) //and user has clicked within the box
{
mousePos = Input.mousePosition; //get mouse position
mousePos.y = Screen.height - mousePos.y; //invert the Y coords
pos.x = mousePos.x - xOffset; // move the box with the mouse
pos.y = mousePos.y - yOffset; // move the box with the mouse
}
}
if (Input.GetMouseButtonUp(0)) //if user releases the mouse button
{
within = false; //set within to false to confirm the user is not clicking anymore
}
}
Comment
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Drawing a GUI box by specifying the two corners 1 Answer
GUI Note taking box 0 Answers
Selection box not working 0 Answers