Keyboard 统一检测键盘输入

Keyboard 统一检测键盘输入,keyboard,2d,unity5,Keyboard,2d,Unity5,我是Unity的新手,一直在网上查阅大量教程/指南。我的问题是,出于某种原因,当我使用下面的代码时,它不会检测到是否单击了键盘。也许我的键盘检测错误了。这是我的密码: using UnityEngine; using System.Collections; public class Player : MonoBehaviour { Vector3 player = GameObject.FindGameObjectWithTag("Player").transform.positio

我是Unity的新手,一直在网上查阅大量教程/指南。我的问题是,出于某种原因,当我使用下面的代码时,它不会检测到是否单击了键盘。也许我的键盘检测错误了。这是我的密码:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    Vector3 player = GameObject.FindGameObjectWithTag("Player").transform.position;

    void Update () {
        if (Input.GetKeyDown(KeyCode.D)) {
            player.x += 0.01F;
        }
    }
}

您的输入代码是正确的,但仍有一些地方不正确。首先,您在任何函数之外编写了一个初始值设定项(静态方法)。请记住,当您在Unity3d C#中执行此操作时,它将始终向您发出警告/错误

如果使用C#不要在构造函数或字段初始值设定项中使用此函数,而是将初始化移到Awake或Start函数

所以首先在两个函数中移动这类行

第二件事是你得到了
Vector3
,并试图将其用作参考,这意味着你得到了一个
Vector3
形式的位置参考,对该变量所做的每一次更改都将有效,但事实并非如此,它不会有效

但是是的,你可以通过获取
转换
游戏对象
来完成,他们会为你完成

第三件也是最后一件事,您试图直接改变
Vector3
组件(在您的例子中是“x”),这对于Unity来说也是不可接受的。您可以使用
newvector3
指定位置,或者创建一个单独的
Vector3
变量,更改该变量,然后将其指定给位置

所以在所有这些地址之后,你的代码应该是这样的

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    Transform player;

    // Use this for initialization
    void Start ()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
    }

    // Update is called once per frame
    void Update ()
    {

        if (Input.GetKeyDown (KeyCode.D)) {

            // Remove one of these two implementations of changing position

            // Either
            Vector3 newPosition = player.position;
            newPosition.x += 0.01f;
            player.position = newPosition;

            //Or
            player.position = new Vector3 (player.position.x + 0.01f, player.position.y, player.position.z);
        }
    }
}

感谢您的详细回复!我已经修改了各个方向的代码。:)