How can i make an object of the new UI, like an button, panel or image draggable? That’s for an inventory system, someone can help me with that?
-
Make your UI object
-
Choose Add Component → Event → Event Trigger
-
Add a new trigger, choose OnDrag
-
Add a listener and call the following script on the dragable object
public void OnDrag(){
transform.position = Input.mousePosition;
}
This works, but it breaks because it assumes the drag event was instigated by the mouse. For reference, here is the component I wrote:
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(RectTransform))]
public class PanelDragBehavior : MonoBehaviour
{
private RectTransform rect;
public void Awake()
{
rect = GetComponent<RectTransform>();
}
public void OnDrag(UnityEngine.EventSystems.BaseEventData eventData)
{
var pointerData = eventData as UnityEngine.EventSystems.PointerEventData;
if (pointerData == null) { return; }
var currentPosition = rect.position;
currentPosition.x += pointerData.delta.x;
currentPosition.y += pointerData.delta.y;
rect.position = currentPosition;
}
}
Simply you can use LeanTouch Lean Dragabble UI script. It available for free in unity store.