Unity - 检测键盘输入
Unity - Detecting keyboard input
我对 Unity 还很陌生,一直在网上查找大量 tutorials/guides。我的问题是,出于某种原因,当我使用下面的代码时,它不会检测是否单击了键盘。也许我做错了键盘检测。这是我的代码:
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# 中执行此操作时,它总是会给您一个 warning/error.
If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
因此,首先在任一函数中移动此类行。
你得到的第二件事 Vector3
并试图将其用作参考,这意味着你获得了 Vector3
形式的位置参考,并且对该变量所做的每项更改都将有效,即不是这样的,不会的。
但是是的,您可以通过 Transform
或 GameObject
来完成,他们会为您完成。
第三也是最后一件事,您正在尝试直接更改 Vector3
组件(在您的情况下为 "x" ),这对于 Unity 也是不可接受的。您可以做的是使用 new Vector3
分配位置或创建一个单独的 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);
}
}
}
我对 Unity 还很陌生,一直在网上查找大量 tutorials/guides。我的问题是,出于某种原因,当我使用下面的代码时,它不会检测是否单击了键盘。也许我做错了键盘检测。这是我的代码:
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# 中执行此操作时,它总是会给您一个 warning/error.
If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
因此,首先在任一函数中移动此类行。
你得到的第二件事 Vector3
并试图将其用作参考,这意味着你获得了 Vector3
形式的位置参考,并且对该变量所做的每项更改都将有效,即不是这样的,不会的。
但是是的,您可以通过 Transform
或 GameObject
来完成,他们会为您完成。
第三也是最后一件事,您正在尝试直接更改 Vector3
组件(在您的情况下为 "x" ),这对于 Unity 也是不可接受的。您可以做的是使用 new Vector3
分配位置或创建一个单独的 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);
}
}
}