从 'if' 语句内部调用 Vector3



很抱歉,如果标题看起来很模糊,用词再好不过了。不过,我可以解释这个问题。

作为一个编程迷,我几乎什么都不懂,然而,这似乎让我感到困惑

if (gotPos == false)
{
// find the target position relative to the player:
Vector3 dir = target.position - this.transform.position;
// keep y direction the same.
dir.y = 0;
// calculate movement at the desired speed:
Vector3 movement = dir.normalized * speed * Time.deltaTime;
gotPos = true;
}
else if (gotPos == true) //anything past this causes errors with Vector3 struct names. ;(
{
if (movement.magnitude > dir.magnitude) movement = dir;
{
// move the character:
cc.Move(movement);
applyGravity();
Debug.Log(target.position);
}
}

每当单击时,我都希望将目标位置设置一次,然后让对象移动到该目标位置。然而,如果不将其包含在if语句中,将不断检查目标位置,对象将始终指向它。然而,"if"语句的问题是,我会收到这样的错误:

显然,Vector3结构确实存在,我如何允许在if语句中使用Vector3结构化?

您需要熟悉术语scope

基本上,变量只存在于最近的大括号{}内,不存在于外部。

在您的情况下,Vector3 movement只存在于if (gotPos == false) {...}部分内部,而不存在于其他任何地方,即不存在于else if (gotPos == true){ ... }内部。

如果你想在两个部分中都使用它,你需要在if语句之前/之外声明它,比如

Vector3 movement;
if (gotPos == false)
{
...
movement = dir.normalized * speed * Time.deltaTime;
...
}
else if (gotPos == true)
{
...
}

假设这段代码必须在一个方法中,那么在这段代码周围可能会有其他大括号=它现在在不同的范围中。在这种情况下,Vector3 movement无法在该方法中生存,并且该分配将是无用的。因此,你需要让它活得更长,并使它成为一个这样的领域:

Vector3 movement;
void mymethod() // this may be different in your code
{
...
if (gotPos == false)
{
...
movement = dir.normalized * speed * Time.deltaTime;
...
}
else if (gotPos == true)
{
...
}
}

看起来您在if语句的else if部分中使用了变量movement,但在if语句的第一部分中声明了它。

换句话说,语句的if部分被完全跳过以进入else if部分,因此变量从未被声明。对于您想在if语句的两个部分中使用的变量,我建议使用类似的方法

Vector3 movement = Vector3.zero;
Vector3 dir = Vector3.zero;
if (gotPos == false)
{
// find the target position relative to the player:
dir = target.position - this.transform.position;
// keep y direction the same.
dir.y = 0;
// calculate movement at the desired speed:
movement = dir.normalized * speed * Time.deltaTime;
gotPos = true;
}
else if (gotPos == true) //anything past this causes errors with Vector3 struct names. ;(
{
if (movement.magnitude > dir.magnitude) movement = dir;
{
// move the character:
cc.Move(movement);
applyGravity();
Debug.Log(target.position);
}
}

您需要在if语句之外声明它们,这样它们就可以在任何一部分中使用。

此外,在else if部分中,movementdir在设置之前都被引用,所以在它们达到这一点之前,您需要将它们设置为某个值,我在示例中将它们设置为Vector3.zero,这样代码就可以工作了。

最新更新