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

相关推荐
有过~12 分钟前
StrokesPlus【电脑鼠标键盘手势软件】v0.5.8.0 中文绿色便携版
计算机外设
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
子蛟7 小时前
Get a free SSL certificate interface.
c#·ssl
虾球xz9 小时前
游戏引擎学习第124天
java·学习·游戏引擎
一只蜗牛儿10 小时前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
tnnnnt13 小时前
今天锐评一下C#
开发语言·c#
Sator114 小时前
C#与AI的交互(以DeepSeek为例)
ai·语言模型·c#