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的方法

相关推荐
玖玥拾3 分钟前
Cocos学习笔记:关卡系统、音频管理与物理控制
游戏引擎·cocos2d
小拉达不是臭老鼠33 分钟前
Unity中的UI系统之UGUI_登陆面板实现
ui·unity
郝学胜-神的一滴43 分钟前
[简化版 GAMES 101] 计算机图形学 11:频域·卷积·抗锯齿
c++·unity·图形渲染·opengl·three·unreal
Ws_1 小时前
WPF 面试题 + 参考答案,偏 C# 桌面端开发高频。
开发语言·c#·wpf
CyL_Cly1 小时前
罗技鼠标驱动下载最新版2026
计算机外设
玖玥拾10 小时前
Cocos学习笔记:滚动视图、关卡系统与本地存储
游戏引擎·cocos2d
曹牧12 小时前
C#:主线程能够捕获到子线程中的异常
开发语言·数据库·c#
元气少女小圆丶17 小时前
SenseGlove Nova 2+Unity开发笔记2
笔记·unity·游戏引擎
jiayong2319 小时前
海量数据处理技术方案与实现原理
大数据·c#·linq
Oiiouui19 小时前
Godot(4.x): 游戏管理器: Godot 内注入数据处理与总接口实现
游戏·游戏引擎·godot