Unity 代码检测单击,双击,拖放

今天小伙伴问我如何自己写一段代码检测 单击 双击 和 拖放.于是就写了这段代码O(∩_∩)O~

 

image

代码如下:

using UnityEngine;

using System.Collections;



public class Test2 : MonoBehaviour {



    public float oneTime;           //检测双击的有效时间

    private int downCount;          //判断是单击还是双击

    private bool currentCheck;      //当前正在检测

    private bool isTuoDong;         //是否拖动

    private bool startTuoDong;      //开始拖动

    void Update () {





        if(Input.GetKeyDown(KeyCode.A))

        {

            downCount++;

            isTuoDong = true;

            if (currentCheck == false) 

            {

                StartCoroutine(CheckDown());

            }

        }



        if (Input.GetKeyUp(KeyCode.A)) 

        {

            isTuoDong = false;

            startTuoDong = false;

        }



        if (startTuoDong) 

        {

            Debug.Log("正在拖动");   

        }

    }



    IEnumerator CheckDown() 

    {

        currentCheck = true;

        yield return new WaitForSeconds(oneTime);



        if (isTuoDong) 

        {

            Debug.Log("拖动");

            startTuoDong = true;



        }else if (downCount >= 2)         //说明是双击

        {

            Debug.Log("双击");

        }

        else if (downCount == 1)    //单击

        {

            Debug.Log("单击");

        }



        downCount = 0;

        currentCheck = false;



    }



}

你可能感兴趣的:(unity)