# 接收键盘输入

下面这段代码演示了在Unity中如何接收按键输入,并输出相关日志。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KeyInput : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.U)) {
            Debug.Log("You clicked U");
        }

        if (Input.GetKey(KeyCode.Y)) {
            Debug.Log("You are pressing Y");
        }
    }
}

这段代码达到的效果就是,当你按下按键U时候,Console面板就会打印"You clicked U"一次。当你按下按键Y并且不松手时候,Console面板就会一直打印"You are pressing Y"。

注意,代码想要执行,就需要绑定到场景中某个游戏对象上面,比如Camera等。