Unity长按Button,显示消息盒子

Button 的长按有很多种,我这里只是写了一种实现方式,通过绑定EventTrigger 来实现的..

Button上的脚本以及,组件添加如下图..

代码如下:

/*********************************************
 *
 *   Title: 
 *
 *   Description: 
 *
 *   Author: jin
 *
 *   Date: 
 *
 *   Modify: 
 * 
 *********************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonInfo : MonoBehaviour
{
    /// <summary>
    /// 点击时间
    /// </summary>
    private float clickTime = 0f;
    /// <summary>
    /// 长按时间
    /// </summary>
    private float clickTimeInterval = .3f;
    /// <summary>
    /// 是否点击
    /// </summary>
    private bool isClick = false;
    /// <summary>
    /// 字体是否显示
    /// </summary>
    private bool infoBoxIsShow = false;
    /// <summary>
    /// 字体控件
    /// </summary>
    public Text infoBoxObj;
    private void Start()
    {
        //点击事件赋初值
        EventTriggerListener.Get(gameObject).onUp += OnClickUp;
        EventTriggerListener.Get(gameObject).onDown += OnClickDown;
    }
    private void Update()
    {
        //点击的时候记录时间
        if (isClick)
        {
            clickTime += Time.deltaTime;
        }
        //如果 该物体没有显示,且超过长按的时间,那么就显示字体
        if (clickTime > clickTimeInterval && !infoBoxIsShow)
        {
            SetInBox(this.name);
        }
    }
    /// <summary>
    /// 点击抬起
    /// </summary>
    /// <param name="go">Go.</param>
    private void OnClickUp(GameObject go)
    {
        //短按触发其他逻辑
        if (clickTime < clickTimeInterval)
        {

        }
        //抬起的时候,将所有变量置为初始值
        isClick = false;
        clickTime = 0;
        infoBoxIsShow = false;
        infoBoxObj.gameObject.SetActive(infoBoxIsShow);
    }
    /// <summary>
    /// 按下
    /// </summary>
    /// <param name="go">Go.</param>
    private void OnClickDown(GameObject go)
    {
        clickTime = 0;
        isClick = true;
    }
    /// <summary>
    /// 显示字体 设置显示的位置
    /// </summary>
    /// <param name="str">String.</param>
    void SetInBox(string str)
    {
        infoBoxIsShow = true;
        infoBoxObj.gameObject.SetActive(infoBoxIsShow);
        infoBoxObj.transform.SetParent(transform);
        infoBoxObj.transform.localPosition = new Vector3(0, 90, 0);
        infoBoxObj.text = str;
    }
}
View Code

这个时候长按,就能看到效果了..

 

posted @ 2019-04-28 15:54  不够自律的人  阅读(328)  评论(0编辑  收藏  举报