首页 > 解决方案 > 声明变量而不覆盖变量的问题

问题描述

在函数内部,我必须声明两个局部浮点变量: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;
    }

}

标签: c#unity3d

解决方案


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

在此处输入图像描述


推荐阅读