Unity 鼠标点击或触摸任意拖动UGUI的方法

在Unity中,如果要通过鼠标拖到UI组件或者触摸移动UI组件,可以使用EventSystems下的方法。

具体实现如下:

新建一个脚本,DragController.cs:

c# 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    private RectTransform tran;
    private Vector2 pointerOffset;

    private void Awake()
    {
        tran = GetComponent<RectTransform>();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        // 计算触摸点与拖动对象的偏移量
        pointerOffset = eventData.position - (Vector2)tran.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        // 更新拖动对象的位置
        tran.position = eventData.position - pointerOffset;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        // 重置偏移量
        pointerOffset = Vector2.zero;
    }
}

然后把该脚本拉到UI组件中,运行后我们可以通过鼠标拖到UI组件,在触摸屏上,我们也可以通过触摸UI组件拖动。

效果如:

Unity 鼠标点击或触摸任意拖动UGUI的方法

相关推荐
小贺儿开发14 分钟前
Unity 局域网遥控幻灯片展示工具 1.0
unity·网络通信·工具·ppt·控制·网页·互动
界面开发小八哥43 分钟前
界面控件DevExpress WinForms中文帮助文档 - 入门指南
ai·c#·.net·devexpress·ui开发·winforms
清风与日月1 小时前
Yitter.IdGenerator:高性能分布式唯一ID生成器详解
分布式·c#·.net·.netcore
影寂ldy2 小时前
C# WinForm TCP-Socket
网络·tcp/ip·c#
czhc11400756633 小时前
2026-08-25 博客:现场排查的 8 个坑
c#
Z5998178413 小时前
c#软件开发学习笔记--WPF(控件、样式)
笔记·学习·c#
格林威3 小时前
C#高位深相机图像保存:12位16位图像保存方案,OpenCvSharp和Halcon实现
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
雪隐4 小时前
WPF + MVVM 实战系列03-MVVM 的边界之争,终于有人画了条“差不多”的线
c#
影寂ldy4 小时前
C# WinForm TCP聊天室(服务端+客户端)
windows·tcp/ip·c#
WarPigs5 小时前
Unity未激活的物体无法响应事件?
java·unity·游戏引擎