using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ResizableUI : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { public RectTransform targetRectTransform; // 需要调整大小的目标物体 private float originalWidth; private Vector2 originalMousePosition; void Start() { // 如果没有指定目标物体,默认使用自身 if (targetRectTransform == null) { targetRectTransform = GetComponent(); } originalWidth = targetRectTransform.rect.width; } // 当鼠标按下时记录初始的鼠标位置 void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) { originalMousePosition = Input.mousePosition; } // 持续拖动时调整物体宽度 void IDragHandler.OnDrag(PointerEventData eventData) { float mouseDelta = Input.mousePosition.x - originalMousePosition.x; float newWidth = Mathf.Max(originalWidth + mouseDelta, 10f); // 最小宽度设置为10 targetRectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, newWidth); } // 拖动结束时更新原始宽度 void IEndDragHandler.OnEndDrag(PointerEventData eventData) { originalWidth = targetRectTransform.rect.width; } }