在不覆盖变量的情况下声明变量的问题

时间:2019-09-25 01:37:03

标签: c# unity3d

在函数内部,我必须在开始时声明两个局部浮点变量:jAxisjumpValuejAxis刚开始就被分配了一个变量,而jumpValue只是float jumpValue;

我稍后在代码中有一个if语句,其中使用了jumpValue。但是,在达到这一点之前,切勿为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;
    }

}

2 个答案:

答案 0 :(得分:0)

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):

enter image description here

答案 1 :(得分:0)

我看不到从何处调用JumpHandler,但是使用bool标志等进行的整个计算对我来说意义不大。

  • 同时无需将该值存储在局部变量jumpValue中。您只想在一个位置使用它,因此只需直接传递相应的值jAxis

  • 由于您刚刚检查了jAxis > 0,因此Mathf.Abs是多余的。

  • 您要将跳转的实际执行推迟到下一次在jumpHandler时再次调用jAxis <= 0时。如果不能满足条件,则直接执行跳转即可。不需要jumpPressed标志。

  • 因为只有在AddForce作为强制倍增器传递给CheckGrounded时,您才允许jAxis也会导致意外的行为。这是一次调用,因为应该在下一帧(或无论在何处调用它)都不再接地。但是,jAxis值可能很小(取决于您在那里使用的轴的类型)。

据我所知,您的代码与此大致相同(无需延迟跳转,只需传入jumpForce * 1而不是jAxis即可)

void JumpHandler()
{
    float jAxis = Input.GetAxis("Jump");
    if(jAxis > 0 && CheckGrounded)
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
    }
}