【Virtual Simulation】In Unity3D, the different status judgments of single-click, double-click, press, and drag of the UI are realized

recommended reading

Hello everyone, I am a Buddhist engineer ☆Tranquil Little Demon Dragon☆ . I update Unity development skills from time to time. If you think it is useful, remember to click three times.

I. Introduction

I wrote an article about clicking, double-clicking, and dragging the mouse in Unity before: [Virtual Simulation] In Unity3D, the different states of mouse clicking, double-clicking, and dragging can be judged .

Some friends asked how to do the single-click, double-click, and drag of the UI?

This article is to realize the different state judgments of single-click, double-click, press, and drag of the UI.

Before we start, let's review the event judgment of the mouse and how to realize the click judgment of the UI.

2. Mouse click event and UI click event

2-1. Mouse click event

The mouse click event is relatively simple, using the mouse input API event:

API events:

Input.GetMouseButtonDown(0);//Right mouse click

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonOnClick : MonoBehaviour
{
    
    
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            Debug.Log("鼠标左键点击");
        }
    }
}

When judging single-click and double-click, it mainly judges the number of clicks.

2-2. UI click event

The click event of the UI needs to inherit the click event interface of the UI, and just rewrite the click event.

UI click event interface:

IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler

Reference Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ButtonOnClick : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    
    
	// 鼠标点击UI
    public void OnPointerClick(PointerEventData eventData)
    {
    
    
    }
	// 鼠标按下UI
    public void OnPointerDown(PointerEventData eventData)
    {
    
    
    }
	// 鼠标离开UI
    public void OnPointerExit(PointerEventData eventData)
    {
    
    
    }
	// 鼠标点击UI后弹起
    public void OnPointerUp(PointerEventData eventData)
    {
    
    
    }
}

Knowing these contents, the next step is to modify the above code.

2-3. Realize different state judgments of UI click, double click, press, and drag

Reference Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ButtonOnClick : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    
    
    // 按压的持续时间
    public float pressDurationTime = 1;
    // 按压的响应次数
    public bool responseOnceByPress = false;
    // 双击的间隔时间
    public float doubleClickIntervalTime = 0.5f;
    // 拖动的间隔时间
    public float dragIntervalTime = 0.2f;
    // 拖动的鼠标间隔距离
    public float dragIntervalPos = 0.01f;

    public UnityEvent onDoubleClick;
    public UnityEvent onPress;
    public UnityEvent onClick;
    public UnityEvent onDrag;

    private bool isDown = false;
    private bool isPress = false;
    private bool isDrag = false;
    private float downTime = 0;

    private float clickIntervalTime = 0;
    private int clickTimes = 0;

    private Vector3 mousePosLast = Vector3.zero;//点击后的拖动位置

    ButtonOnClick btn;

    void Start()
    {
    
    
        btn = GetComponent<ButtonOnClick>();
        btn.onClick.AddListener(Click);
        btn.onPress.AddListener(Press);
        btn.onDoubleClick.AddListener(DoubleClick);
        btn.onDrag.AddListener(Drag);
    }

    void Click()
    {
    
    
        Debug.Log("单击");
    }

    void Press()
    {
    
    
        Debug.Log("按压");
    }

    void DoubleClick()
    {
    
    
        Debug.Log("双击");
    }

    void Drag()
    {
    
    
        Debug.Log("拖动");
    }

    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(0))
        {
    
    
            Debug.Log("鼠标左键点击");
        }

        if (isDown)
        {
    
    
            if (responseOnceByPress && isPress)
            {
    
    
                return;
            }
            downTime += Time.deltaTime;
            isDrag = Vector3.Distance(Input.mousePosition, mousePosLast) > dragIntervalPos;
            if (downTime > pressDurationTime && !isDrag)
            {
    
    
                isPress = true;
                onPress.Invoke();
            }
            if (downTime > dragIntervalTime && isDrag)
            {
    
    
                onDrag.Invoke();
            }
        }
        if (clickTimes >= 1)
        {
    
    
            clickIntervalTime += Time.deltaTime;
            if (clickIntervalTime >= doubleClickIntervalTime)
            {
    
    
                if (clickTimes >= 2)
                {
    
    
                    onDoubleClick.Invoke();
                }
                else
                {
    
    
                    onClick.Invoke();
                }
                clickTimes = 0;
                clickIntervalTime = 0;
            }
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
    
    
        if (!isPress)
            clickTimes += 1;
        else
            isPress = false;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
    
    
        isDown = true;
        downTime = 0;
        mousePosLast = Input.mousePosition;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
    
    
        isDown = false;
        isPress = false;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
    
    
        isDown = false;
    }
}

Renderings:
insert image description here

3. Postscript

If you find this article useful, don’t forget to follow it, follow it so you don’t get lost, and continue to share more Unity dry goods articles.


Your likes are your support for bloggers, please leave a message if you have any questions:

The blogger's homepage has contact information.

The blogger also has many treasured articles waiting for your discovery:

column direction Introduction
Unity3D development small game Small Game Development Tutorial Share some small games developed using the Unity3D engine, and share some tutorials for making small games.
Unity3D from entry to advanced getting Started Get inspiration from self-study Unity, summarize the route of learning Unity from scratch, and have knowledge of C# and Unity.
UGUI for Unity3D UGUI A full analysis of Unity's UI system UGUI, starting from the basic controls of UGUI, and then comprehensively teaching the principles of UGUI and the use of UGUI.
Reading data of Unity3D file read Use Unity3D to read txt files, json files, xml files, csv files, and Excel files.
Data collection of Unity3D data set Array collection: Knowledge sharing of data collections such as arrays, lists, dictionaries, stacks, and linked lists.
VR/AR (Virtual Simulation) Development of Unity3D virtual reality Summarize the common virtual simulation needs of bloggers and give case explanations.
Plugin for Unity3D plug-in Mainly share some plug-in usage methods used in Unity development, plug-in introduction, etc.
Daily development of Unity3D daily record It is mainly used by bloggers in daily development, methods and skills used, development ideas, code sharing, etc.
Daily BUG of Unity3D daily record Record the bugs and pitfalls encountered during the development of the project using the Unity3D editor, so that later generations can have some reference.

Guess you like

Origin blog.csdn.net/q764424567/article/details/130347907