c# - 声明变量而不覆盖变量的问题
问题描述
在函数内部,我必须声明两个局部浮点变量:jAxis
并且jumpValue
在开始时。 jAxis
在开始时立即分配一个变量,而jumpValue
只是float jumpValue;
我if
稍后在代码中有一个语句,其中jumpValue
使用了 in 。但是,jumpValue
在达到这一点之前,永远不应取消分配值。编译器不同意底部附近的计算use of unassigned local variable jumpValue
错误。Vector3
这是我的相关代码:
void JumpHandler()
{
float jAxis = Input.GetAxis("Jump");
float jumpValue;
//if pressed
if (jAxis > 0)
{
bool isGrounded = CheckGrounded();
if (isGrounded)
{
jumpValue = jAxis;
if (!jumpPressed)
{
jumpPressed = true; //Pressed jump
}
}
else
{
jumpValue = 0;
}
}
else if (jumpPressed)
{
rb.AddForce(new Vector3(0, Math.Abs(jumpValue) * jumpForce * 1, 0) , ForceMode.VelocityChange);//Absolute value to prevent weird cases of negative jAxis
//jump key not pressed
jumpPressed = false;
jumpValue = 0;
}
else
{
jumpPressed = false;
}
}
解决方案
if(jumpPressed)
块与块互斥是没有意义的if (jAxis > 0)
。删除else
之前的if (jumpPressed)
.
此外,您应该初始化jumpValue
为,0f
因为编译器无法自行识别jumpPressed
只有在设置时才jumpValue
为真。
您不需要将 else 块设置jumpPressed
为 false,因为如果它在该块中,它已经是 false。
总而言之,这可能看起来像这样:
void JumpHandler()
{
float jAxis = Input.GetAxis("Jump");
float jumpValue = 0f;
//if pressed
if (jAxis > 0)
{
bool isGrounded = CheckGrounded();
if (isGrounded)
{
jumpValue = jAxis;
if (!jumpPressed)
{
jumpPressed = true; //Pressed jump
}
}
else
{
jumpValue = 0;
}
}
if (jumpPressed)
{
rb.AddForce(
//Absolute value to prevent weird cases of negative jAxis
new Vector3(0, Mathf.Abs(jumpValue) * jumpForce, 0),
ForceMode.VelocityChange);
//jump key not pressed
jumpValue = 0;
jumpPressed = false;
}
}
CheckGrounded
这会产生这样的输出(使用一个返回一次的虚拟方法true
):
推荐阅读
- sql - Redshift SQL - 计算组内重复值的序列
- nginx - Nginx 在动态子文件夹中部署静态文件
- python-3.x - 如何在views.py中获取ForeignKey的值?
- rpc - 如何实现:主机A将数据写入其本地nvme磁盘,然后主机B通过远程访问磁盘读取值?
- reactjs - Reactjs 和 Firebase:用户和管理员的登录界面或单独的登录界面?
- java - 在一个自定义 Jackson JsonSerializer 中序列化两个字段时如何避免重复 JSON 字段?
- php - Xdebug 启动连接,然后自动关闭
- javascript - Redux Thunk 数据存储为字符串而不是对象
- flutter - Flutter Mobile:使用 Mocks 测试 Algolia 包不起作用
- reactjs - 3d-react-carousel 停止反应动画