ugui 的拖拽在游戏中经常用到,只要继承相关接口并实现就能完成. 并且我这个是加了范围检测的,希望能帮到你!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragCheck : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public bool _isCheckZone = false;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
// begin dragging
public void OnBeginDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
// during dragging
public void OnDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
// end dragging
public void OnEndDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
/// <summary>
/// set position of the dragged game object
/// </summary>
/// <param name="eventData"></param>
private void SetDraggedPosition(PointerEventData eventData)
{
var rt = gameObject.GetComponent<RectTransform>();
// transform the screen point to world point int rectangle
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
{
float x = globalMousePos.x, y = globalMousePos.y;
Debug.Log("x:" +x +"y:" +y);
rt.position = _isCheckZone ? CheckPos(x,y) : new Vector2(x,y);
}
}
Vector2 CheckPos(float x, float y)
{
if (x < 120)
x = 120;
else if (x > 600)
x = 600;
if (y > 920)
y = 920;
else if (y < 320)
y = 320;
return new Vector2(x, y);
}
}

如果限制范围,就不会出框,至于范围边界,自己用的时候设置一下就行了.