Drag-able and resisable Window

Is it possible to simply implement the ability to drag and resize a canvas element or an element within it?

I created a panel and within that a whole bunch of controls. Found that with the anchors correctly setup you I can resize the panel and everything insides resizes perfectly, the new UI is quite impressive.

Here’s some simple dragging code:

using UnityEngine;
using UnityEngine.EventSystems;

public class DragBar : MonoBehaviour, IDragHandler
{
    Transform panel;

    void Awake()
    {
        panel = gameObject.transform.parent;
    }

    public void OnDrag(PointerEventData data)
    {
        float x = data.position.x;
        float y = data.position.y;
        panel.position = new Vector3(x, y, 0f);
    }
}

Put the object you use as a drag handle (an image would work best) as a child of a panel or whatever. Note that this puts the hierarchy at the mouse pointer according to the pivot point of the panel. You can move that around easily enough in 2D view, but it could use improvements. Make it adjust the position as it’s picked up so it doesn’t just jump to the pointer, use the pivot point of the handle, make the script take the panel as a variable etc.

Resizing wouldn’t be much different for the simplest case, where you have a resize corner for the panel.

1 Like

Just had chance to try it, works really well, thanks.