Unity3D基础9:获取鼠标键盘输入

 

前文:https://blog.****.net/Jaihk662/article/details/86751079(C#脚本)

一、获取键盘输入

相关API(其中KeyCode为键码,例如空格键就是KeyCode.Space):

  • Input.GetKey(KeyCode):按下某键后,持续返回 ture
  • Input.GetKeyDown(KeyCode):按下某键的一瞬间返回 true
  • Input.GetKeyUp(KeyCode):松开某键的一瞬间返回 true
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Text1: MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Debug.Log("Start");     //输出调试
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Debug.Log("你压着空格不放");
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("你按下了空格");
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Debug.Log("你松开了空格");
        }
        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("你压着A不放");
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("你按下了A");
        }
        if (Input.GetKeyUp(KeyCode.A))
        {
            Debug.Log("你松开了A");
        }
    }
}

很显然必须在Update()中使用这些方法,不然没有意义

运行后效果如下:

Unity3D基础9:获取鼠标键盘输入

 

二、获取鼠标输入

相关API(0:鼠标左键;1:鼠标右键;2:鼠标中键)

  • Input.GetMouseButton(0/1/2):按下某键后,持续返回 true
  • Input.GetMouseButtonDown(0/1/2):按下某键的一瞬间,返回 true
  • Input.GetMouseButtonUp(0/1/2):松开某键的一瞬间,返回 true
if (Input.GetMouseButton(1))
{
    Debug.Log("你压着鼠标右键不放");
}
if (Input.GetKeyDown(KeyCode.Space))
{
    Debug.Log("你按下了鼠标右键");
}
if (Input.GetKeyUp(KeyCode.Space))
{
    Debug.Log("你松开了鼠标右键");
}

一个Unity3D错误:error CS0101: The namespace 'global::' already contains a definition for `xxxxx'

解决方案:编译错误,某个命名空间下有重复的标识符,看下函数名是否冲突等等,例如一个物体只能有一个Start()。.cs文件重名也有可能出现这种错误