輸入與控制操作Unity為開發者提供了Input類庫,其中包括鍵盤事件、鼠標事件和觸摸事件等一切跨平台所需要的控制事件。
一、鍵盤事件
1、按下事件
Input.GetKeyDown():如果按鍵被按下,該方法將返回true,沒有按下則返回false。
// Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.A)) { Debug.Log("您按下了A鍵"); } if (Input.GetKeyDown(KeyCode.B)) { Debug.Log("您按下了B鍵"); } if (Input.GetKeyDown(KeyCode.Backspace)) { Debug.Log("您按下了退格鍵"); } if (Input.GetKeyDown(KeyCode.F1)) { Debug.Log("您按下了F1鍵"); } }
直接把代碼附加到主攝像頭
2、抬起事件
Input.GetKeyUp()方法得到抬起事件。方法和按下事件相同。
#region 抬起事件 if (Input.GetKeyUp(KeyCode.A)) { Debug.Log("您抬起了A鍵"); } if (Input.GetKeyUp(KeyCode.B)) { Debug.Log("您抬起了B鍵"); } if (Input.GetKeyUp(KeyCode.Backspace)) { Debug.Log("您抬起了退格鍵"); } if (Input.GetKeyUp(KeyCode.F1)) { Debug.Log("您抬起了F1鍵"); } #endregion
3、長按事件
監聽鍵盤中某個按鍵是否一直處於被按下的狀態,使用Input.GetKey()方法來判斷。
#region 長按事件 int count = 0; if (Input.GetKeyDown(KeyCode.A)) { Debug.Log("A按下一次"); } if (Input.GetKey(KeyCode.A)) { count++; Debug.Log("A被連續按了:"+count); } if (Input.GetKeyUp(KeyCode.A)) { //抬起后清空幀數 count = 0; Debug.Log("A按鍵抬起"); } #endregion
4、任意鍵盤事件
在常見游戲中,讀取完資源后,會提示玩家按任意鍵繼續操作anyKeyDown
二、鼠標事件
和鍵盤事件一樣,鼠標一般只有3個按鍵,左鍵、右鍵和中鍵。具體如下:
1、按下事件
Input.GetMouseButtonDown()來判斷鼠標哪個按鍵被按下:如果參數為0,則代表鼠標左鍵被按下,
參數為1代表鼠標右鍵被按下,
參數為2代表鼠標中鍵被按下
2、抬起事件
Input.GetMouseButtonUp()方法監聽鼠標按鍵的抬起事件
3、長按事件
使用Input.GetMouseButton()方法監聽鼠標某個按鍵是否一直處於按下狀態。
14-03-10
GUI.Button 補充
當使用tooltip時 需要添加一個label這點和webform不一樣。
using UnityEngine; using System.Collections; public class ButtonScript : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { //if (Time.time%2 > 1) //{ if (GUI.Button(new Rect(10f, 10f, 100f, 60f), "Hello")) { print("你單擊了Hello"); } GUI.Button(new Rect(10f, 80f, 100f, 60f), new GUIContent("我是按鈕","這是一個提示")); GUI.Label(new Rect(10f, 160f, 100f, 60f), GUI.tooltip); //} } }
效果: