如何知道用户何时持有UI按钮?

时间:2015-04-03 22:08:26

标签: c# unity3d

检测按钮OnClick事件非常容易,但我无法弄清楚如何检测使用何时开始和停止触摸按钮。怎么办呢?

这就是我现在正在尝试的事情:

public class Touching : MonoBehaviour {
    public static bool mouseDown;
    public float timeMouseDown;

    void Update(){
        if (mouseDown) {
            timeMouseDown += 1;
            Debug.Log ("meditar");
        }
    }

    public void OnPointerDown(PointerEventData eventData){
        Debug.Log ("OnPointerDown");
        mouseDown = true;
    }

    public void OnPointerUp(PointerEventData eventData){
        Debug.Log ("OnPointerUp");
        mouseDown = false;
        timeMouseDown = 0;
    }
}

2 个答案:

答案 0 :(得分:3)

您需要3个变量:boolean(您已经拥有),DateTime(用户点击按钮的那一刻)和TimeSpan(点击持续时间)。< / p>

boolean mouseDown;
DateTime startTime;
TimeSpan clickDuration;

public void OnPointerDown(PointerEventData eventData){
    Debug.Log ("OnPointerDown");
    mouseDown = true;
    startTime = DateTime.Now;
}

public void OnPointerUp(PointerEventData eventData){
    Debug.Log ("OnPointerUp");
    mouseDown = false;
    clickDuration = DateTime.Now - startTime;
}

正如Huacanacha所说,使用Unity的特定Time函数而不是泛型DateTimeTimeSpan可能会更快。您可以尝试这两种方法,并衡量对性能的影响。

答案 1 :(得分:-1)

你可以在mousedown上启动一个线程然后告诉线程在mouseup停止。这将使表单保持响应。 它看起来像这样:

using System.threading
class my class
{

private thread thread0(functiontoloop);

mousedownevent
{
    thread0.start();
}

private void funtiontoloop()
{
    do something here
}


mouseupevent 
{
     thread0.Abort();
//  or u could use
 thread0.suspend();  // that way you could resume if needed

}
}

并使用它:

using System.Threading;
Thread t;
private void btn_Xmas_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
        ThreadStart del=new ThreadStart(dothis);
       t=new Thread(del);
    t.Start();
}

private void btn_Xmas_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
    t.Abort();
}
public void dothis()
{
    while(true)
    {
              this.x=this.x+10;     
                                                               this.crimsonModel.writeStringToAll("newX:"+x.ToString());
        }
}