本文講述了怎樣進行鼠標和鍵盤的輸入信息檢測。外部設備輸入檢測需要每一幀運行,所以檢測的函數需要寫在Update函數中。本文講的內容比較簡單,直接上代碼吧。
using UnityEngine;
using System.Collections;
public class InputMethod : MonoBehaviour {
int mPressMouseLeft = 0;
int mPressMouseRight = 0;
int mPressMouseMiddle = 0;
void Start () {
}
void Update () {
//鼠標按下事件
if (Input.GetMouseButtonDown(0))
{
Debug.Log("按下了鼠標左鍵");
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("按下了鼠標右鍵");
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("按下了鼠標中鍵");
}
//鼠標擡起事件
if (Input.GetMouseButtonUp(0))
{
Debug.Log("擡起了鼠標左鍵");
}
if (Input.GetMouseButtonUp(1))
{
Debug.Log("擡起了鼠標右鍵");
}
if (Input.GetMouseButtonUp(2))
{
Debug.Log("擡起了鼠標中鍵");
}
//鼠標長按事件
if (Input.GetMouseButton(0))
{
mPressMouseLeft++;
}
else
{
if (mPressMouseLeft > 0)
{
Debug.Log("鼠標左鍵按下的幀數爲: " + mPressMouseLeft.ToString());
}
mPressMouseLeft = 0;
}
if (Input.GetMouseButton(1))
{
mPressMouseRight++;
}
else
{
if (mPressMouseRight > 0)
{
Debug.Log("鼠標右鍵按下的幀數爲: " + mPressMouseRight.ToString());
}
mPressMouseRight = 0;
}
if (Input.GetMouseButton(2))
{
mPressMouseMiddle++;
}
else
{
if (mPressMouseMiddle > 0)
{
Debug.Log("鼠標中鍵按下的幀數爲: " + mPressMouseMiddle.ToString());
}
mPressMouseMiddle = 0;
}
//鍵盤按下事件
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("按下了空格");
}
//鍵盤擡起事件
if (Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("擡起了空格");
}
//鍵盤長按事件
if (Input.GetKey(KeyCode.Space))
{
Debug.Log("空格正在被按下狀態");
}
}
}
運行後,點擊鼠標和空格鍵,會看到如下結果。