有没有一种方法可以在unity 3d中拖放UI按钮



在unity 3d中有拖放UI按钮的方法吗?

我可以为一个按钮添加两个功能吗?第一个当它被正常点击时,它会做一些事情。第二次点击并按住它时,它可以被拖放到屏幕上的其他地方吗?

这是我到目前为止的代码,但它对按钮不起作用。

void Update()
{
if (isDragged)
{
transform.position =  Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
public void OnMouseOver()
{
if (Input.GetMouseButtonDown(0))
{
isDragged = true;
}

}
public void OnMouseUp()
{
isDragged = false;
}

您可以使用unity内置接口,

使用IPointerClickHandler在点击时做一些事情,并实现另外三个处理拖动的界面,即IBeginDragHandlerIDragHandlerIEndDragHandler

public class Example : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
{
//Detect if a click occurs
public void OnPointerClick(PointerEventData pointerEventData)
{
Debug.Log(name + " Game Object Clicked!");
}
public void OnBeginDrag(PointerEventData eventData)
{
}
public void OnDrag(PointerEventData data)
{
}
public void OnEndDrag(PointerEventData eventData)
{
}
}

参考文献:https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.IDragHandler.html

最新更新