How do i drag a GUI.Button ?

how do i drag a GUI button ?

yeah its a noob question but seeing as i have never used any drag function…lol

That’s what whydoidoit meant:

public class TestClass : MonoBehaviour
{
    Rect buttonRect = new Rect(10, 10, 100, 20);
    bool buttonPressed = false;

    void OnGUI()
    {
        if(buttonRect.Contains(Event.current.mousePosition))
        {
            if(Event.current.type == EventType.MouseDown)
            {
                buttonPressed = true;
            }

            if(Event.current.type == EventType.MouseUp)
            {
                buttonPressed = false;
            }
        }

        if(buttonPressed && Event.current.type == EventType.MouseDrag)
        {
            buttonRect.x += Event.current.delta.x;
            buttonRect.y += Event.current.delta.y;
        }

        GUI.Button(buttonRect, "Draggable Button");
    }
}

It checks if you pressed the mouse button while the cursor is over the GUI button, and then, if it’s pressed and dragged, it applies movement delta of the mouse to the button’s Rect. Here you can only drag the button if you previously pressed it. This way you can create your own GUI controls and their behaviour. Hope it helps.

I won’t pretend this is the cleanest way to do this, but it works. Add some clamping to the values and you’ll have something solid.

public class UserInterface : MonoBehaviour {
	public Rect playerPositionRect = new Rect(0, 151, 200, 50);
	private Vector2 currentDrag = new Vector2();

	void Start () {
	
	}
	
	void Update () {
	
	}
	
	void OnGUI(){
		GUI.Box (playerPositionRect, "Pos: " + playerPosition);
		
		Vector2 screenMousePosition = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
		if (currentDrag.sqrMagnitude != 0 || playerPositionRect.Contains(screenMousePosition)) {
			if (Input.GetMouseButtonDown(0)) {
				currentDrag = screenMousePosition;
			} else if (Input.GetMouseButton(0)) {
				playerPositionRect.x += (screenMousePosition.x - currentDrag.x);
				playerPositionRect.y += (screenMousePosition.y - currentDrag.y);
				
				currentDrag = screenMousePosition;
			} else {
				currentDrag.x = 0;
				currentDrag.y = 0;
			}
		}
	}
}

AngryAnt created a very nice tutorial about drag’n’drop,
http://angryant.com/2009/09/18/gui-drag-drop/
He has in that example how to make dragging in ediotor as well as in the scene.

If you’re willing to use NGUI, I made a blog post outlining how to do that here. It can be done in a matter of moments with no coding required.

Basically, you add a Collider to the element you want the user to click to drag, add the UIDragObject script on to that object, and drag the object you want to move around to the UIDragoObject’s “Target” parameter.