C#多个If语句
我一直在Unity2D工作,试图为自上而下的RPG编写编程。我遇到的问题是C#似乎不理解我的if语句。我设置了多个if语句和一个else语句,但是else语句只对写在上面的语句生效。它有点像其他if语句作为单独的代码行被推到一旁,尽管我希望else对所有if语句都有效。如果这听起来让人困惑,我很抱歉,如果你能找出问题,我会把我的代码放在下面C#多个If语句,c#,unity3d,C#,Unity3d,我一直在Unity2D工作,试图为自上而下的RPG编写编程。我遇到的问题是C#似乎不理解我的if语句。我设置了多个if语句和一个else语句,但是else语句只对写在上面的语句生效。它有点像其他if语句作为单独的代码行被推到一旁,尽管我希望else对所有if语句都有效。如果这听起来让人困惑,我很抱歉,如果你能找出问题,我会把我的代码放在下面 // Update is called once per frame void Update () { //directional movemen
// Update is called once per frame
void Update () {
//directional movement
if (Input.GetKey (KeyCode.W)) {
this.transform.Translate(Vector2.up * speed);
anim.SetBool ("moving", true);
}if (Input.GetKey (KeyCode.A)) {
this.transform.Translate(Vector2.right * -speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", false);
}if (Input.GetKey (KeyCode.S)) {
this.transform.Translate (Vector2.up * -speed);
anim.SetBool ("moving", true);
}if (Input.GetKey (KeyCode.D)) {
this.transform.Translate (Vector2.right * speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", true);
} else{
anim.SetBool ("moving", false);
}
}
在aush的回答中,您可以使用一系列的
else if
语句。或者,考虑<代码>开关<代码> < /P>
KeyCode kc = Input.GetKey();
switch (kc) {
case KeyCode.W:
this.transform.Translate(Vector2.up * speed);
break;
case KeyCode.A:
this.transform.Translate(Vector2.right * -speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", false);
break;
case KeyCode.S:
this.transform.Translate (Vector2.up * -speed);
anim.SetBool ("moving", true);
break;
case KeyCode.D:
this.transform.Translate (Vector2.right * speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", true);
break;
default:
anim.SetBool ("moving", false);
break;
}
我个人觉得开关块比一系列其他ifs更容易阅读。如果不满足任何情况,将执行默认设置
此外,如果使用
或开关,则代码将不允许同时解析多个按钮按下,例如向上和向右。如果你没有对角线,那么这是有意义的。你可以使用一系列的else If
语句,就像aush的答案一样。或者,考虑<代码>开关<代码> < /P>
KeyCode kc = Input.GetKey();
switch (kc) {
case KeyCode.W:
this.transform.Translate(Vector2.up * speed);
break;
case KeyCode.A:
this.transform.Translate(Vector2.right * -speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", false);
break;
case KeyCode.S:
this.transform.Translate (Vector2.up * -speed);
anim.SetBool ("moving", true);
break;
case KeyCode.D:
this.transform.Translate (Vector2.right * speed);
anim.SetBool ("moving", true);
anim.SetBool ("facingRight", true);
break;
default:
anim.SetBool ("moving", false);
break;
}
我个人觉得开关块比一系列其他ifs更容易阅读。如果不满足任何情况,将执行默认设置
此外,如果使用或开关,则代码将不允许同时解析多个按钮按下,例如向上和向右。如果你没有对角线,那么这是有意义的。这是C的预期行为,使用If-ELSE If-ELSE这是C的预期行为,使用If-ELSE If-ELSE