C# - Draggable 4.6 UI?
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? :)
Complete solution for 2016 ...
http://stackoverflow.com/a/37473953/294884
extremely elegant, amazingly simple. Copy and paste.
Answer by Kiwasi · Dec 03, 2014 at 11:17 PM
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; }
Thanks a TON!!! $$anonymous$$ade my task SO much simpler.
OnDrag doesn't appear anymore in the Event Trigger list, what would be the correct one now?
Answer by Justin L · Aug 24, 2015 at 11:40 AM
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;
}
}
Thank you for your reply, but I need an easy way to drag a GUI element, like you would do in Windows/OSX/Linux. I've tried some things already, but my knowledge of the new UI system and C# in general is not sufficient to come up with a good solution. If you, or anyone else, has a simple solution, or something that will bring me halfway, it'll be greatly appreciated!
Little note: I do not just copy-paste, but try to learn and understand everything I read and try! ;)
Answer by prasanthvel · Nov 01, 2017 at 06:12 AM
Simply you can use LeanTouch Lean Dragabble UI script. It available for free in unity store.