c# - C# 统一 if 语句
问题描述
我刚开始使用unity,以前从未使用过C#。下面的代码引发了错误The name 'direction' does not exist in the current context
,我不知道为什么。我确信这非常明显,但我对这一切都很陌生。
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);
}
解决方案
让我试着解释一下:
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);
尝试在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);
}
推荐阅读
- css - SVG 在 WP Elementor 中有两种颜色作为徽标
- java - 为什么我使用 Netty 在此端口上创建了 UDP 监视器时端口的状态未侦听?
- javascript - 进行更改时,如何更新我的 serviceworker 脚本以更新缓存页面?
- javascript - Javascript XMLHTTPRequest 使用标头中未定义的协议发送
- python - 记录加速度计(X、Y 和 Z)读数的特定运动模式
- c# - 是否可以在此方法中移动我的返回值?
- spring - Hibernate 连接池超时,最终应用服务器挂起
- c++ - 放置新的 &data[i] 而不是 data + i 是 UB 吗?
- c# - C# ExcelDataReader 修剪标题列
- javascript - Express node.js - 渲染功能是否有承诺?