Unity教程之-Unity3d中模拟鼠标单击、双击

 

在游戏中单击、双击在平时的应用中还是比较常见的,然而Unity3d并没有提供相应的 API 函数,所以我们要处理鼠标的双击事件,只得去编写代码去模拟,但实现起来并不麻烦。下面贴上代码


using UnityEngine;
using System.Collections;

public class MouseResponseManager
{
public static void Register(GameObject objectItem, Action clickCallback, Action doubleCallback)
{
if(objectItem == null)
{
objectItem = new GameObject();
objectItem.name = "MouseResponseItem";
}
MouseResponseItem mouseResponseItem = objectItem.AddComponent<MouseResponseItem> ();
mouseResponseItem.Init (clickCallback, doubleCallback);
}
}
public class MouseResponseItem : MonoBehaviour
{
private bool mouseDownStatus;
private int mouseDownCount;
private float lastTime;
private float currentTime;

private Action clickCallback;
private Action doubleCallback;

public void Init(Action clickCallback, Action doubleCallback)
{
this.clickCallback = clickCallback;
this.doubleCallback = doubleCallback;
}

void Update()
{
if(Input.GetMouseButtonDown(0))
{
if(!this.mouseDownStatus)
{
this.mouseDownStatus = true;
//Debug.Log("Click !");
if(this.clickCallback != null) this.clickCallback();

// 如果按住数量为 0
if(this.mouseDownCount == 0)
{
// 记录最后时间
this.lastTime = Time.realtimeSinceStartup;
}
this.mouseDownCount ++;
}
}

if(Input.GetMouseButtonUp(0))
{
//Debug.Log("Up !");
this.mouseDownStatus = false;
}

if(this.mouseDownStatus)
{
//Debug.Log("Hold !");
if(this.mouseDownCount >= 2)
{
this.currentTime = Time.realtimeSinceStartup;
if(this.currentTime - this.lastTime < 0.3f)
{
this.lastTime = this.currentTime;
this.mouseDownCount = 0;
//Debug.Log("Double Click");
if(this.doubleCallback != null) this.doubleCallback();
}
else
{
// 记录最后时间
this.lastTime = Time.realtimeSinceStartup;
this.mouseDownCount = 1;
}
}
}
}
}

测试代码如下


using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
void Start()
{
MouseResponseManager.Register(null, ()=>
{
Debug.Log("click");
}, ()=>{
Debug.Log("double click");
});
}

void OnGUI ()
{
GUI.Label(new Rect(15, 15,300, 100), "在舞台上单击/双击查看输出!");
}

}

好了,本篇unity3d教程关于Unity3d中模拟鼠标单击、双击到此结束,下篇我们再会!