- Home /
how to active a button after drag?
Hi,
My desired flowchart is the following:
1- Press a GUIRepeatButton and drag its texture over the screen.
2- If you release the mouse when you are over another Button copy the texture on the second button.
My problem is a button only answers true if you press and release above him and not only when you release. Any suggestions? My code is the following:
public bool dragging = false;
public Texture2D dragged;
void onGUI(){
if (GUI.RepeatButton (new Rect (Screen.width/8*5 - Screen.width/32,Screen.height/37*32,Screen.width/8,Screen.height/37*9), "", buttonCircle ))
{
dragging = true;
dragged = circle;
}
if (dragging)
{
if (Input.GetMouseButtonUp(0))
{
dragging = false;
}else
{
GUI.DrawTexture(new Rect(Input.mousePosition.x - Screen.width/8/2,Screen.height - Input.mousePosition.y - Screen.height/37*9/2,Screen.width/8,Screen.height/37*9), dragged, ScaleMode.StretchToFill , true, 0);
}
}
Answer by robertbu · Apr 30, 2014 at 12:48 AM
First 'onGUI' should be 'OnGUI', so this code would not be executed. Second, you don't want to use the Input class here. Use the Event class. Something like:
void OnGUI() {
Event e = Event.current;
if (e.type == EventType.MouseUp) {
Debug.Log("Mouse button lifted");
}
}
My problem is a button is only answer true if you press and realesed over him and not only realesed
If this is your specific question, a solution I've used is to test the position of the mouse when the button is released. If it is within the confines of the button, then trigger it. You don't even need to use a button if the only way to trigger it is drag and drop. You can just use a DrawTexture(). So you put the Rect into the variable:
Rect rectTarget = new Rect(0,0,100,50);
You can then test the rect when the mouse button comes up:
if (rectTarget.Contains(e.mousePosition)) {
// Do whatever.
}
Answer by Lombard · May 01, 2014 at 02:18 PM
It's a cool idea, and it works perfectly. Btw, I still have some questions Why using events? I'm still using input and it works properly... Is there any difference? Another problem i found is the mouse have the origin at the bottom of the screen so my code finally its like that:
if (Input.GetMouseButtonUp(0)){ if (positions[0].Contains(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y))) { //Do things } dragging = false; }else{ //Keep Dragging
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613143913im_/https://answers.unity.com/themes/thub/images/avi.jpg)