[英]C# unity if statement
I have just started with unity, and have never used C# before.我刚刚开始使用 unity,之前从未使用过 C#。 The code below raises the error The name 'direction' does not exist in the current context
and I have no clue why.下面的代码引发错误The name 'direction' does not exist in the current context
,我不知道为什么。 I'm sure it's super obvious but I am new to all this.我确定这非常明显,但我对这一切都很陌生。
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
if (moveVertical != 0 || moveHorizontal != 0) {
if (moveVertical > 0) {
string direction = "up";
} else if (moveVertical < 0) {
string direction = "down";
} else if (moveHorizontal > 0) {
string direction = "right";
} else if (moveHorizontal < 0) {
string direction = "left";
} else {
string direction = "###";
}
Debug.Log(direction);
}
Let me try to explain a bit:让我试着解释一下:
if (moveVertical > 0) {
// You are declaring this for the if block
// This is declared locally here
string direction = "up";
// Direction exists in the if block
Debug.Log(direction);
}
// Direction does not exist here as it is out of the block
Debug.Log(direction);
Try to declare outside of the if
blocks:尝试在if
块之外声明:
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
string direction = "";
if (moveVertical != 0 || moveHorizontal != 0) {
if (moveVertical > 0) {
direction = "up";
} else if (moveVertical < 0) {
direction = "down";
} else if (moveHorizontal > 0) {
direction = "right";
} else if (moveHorizontal < 0) {
direction = "left";
} else {
direction = "###";
}
Debug.Log(direction);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.