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

相关推荐
浅陌sss9 小时前
Xlua中C#引用Lua变量,导致Lua侧的GC无法回收的原因及解决方法
c#·lua
棉晗榜9 小时前
c#模拟鼠标点击左键
c#
爱吃香蕉的阿豪10 小时前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
晚秋大魔王12 小时前
C# 添加图标
c#·visual studio code
浅陌sss12 小时前
Unity中可靠的UDP实现
unity
shepherd枸杞泡茶13 小时前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
yuanpan13 小时前
C#的async异步方法里如果使用了await,那么它跟同步方法有什么区别?
开发语言·c#
虾球xz15 小时前
游戏引擎学习第107天
学习·游戏引擎
虾球xz15 小时前
游戏引擎学习第105天
前端·学习·游戏引擎
CodeCraft Studio16 小时前
.NET版PDF处理控件Aspose.PDF教程:在 C# 中将 TIFF 文件转换为 PDF
pdf·c#·.net