Unity3D笔记十六 输入输出-键盘事件、鼠标事件

  输入与控制操作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);
        //} 
    }
}

效果:


作者:PEPE
出处:http://pepe.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/PEPE/p/3531959.html