Vector3 assigned in if-statement is being reverted

Here is my current code:

    void FixedUpdate() {
        Simulate();
    }

    private void Simulate() {
        
        if(Input.GetKey(KeyCode.Mouse0) == true){
            Vector3 gravity = new Vector3(1f, 0f, 0f);
            Debug.Log(gravity);
        }
        
        Debug.Log(gravity);
        rb.AddForce(gravity * gravityMagnitude, ForceMode.Force);
    }

Besides declaring the variables, they are never mentioned anywhere else in the script. When I run the code and press left click, the first Debug statement logs the vector as (1, 0, 0) but the second debug statement always logs the vector as (0, 0, 0) and no force is applied.

Line 8 in the example is declaring a new variable with the name of gravity which is scoped only to that method, then afterwards you are using a different variable called gravity, likely the one scoped to the class itself.

So on line 8, remove the Vector3 before gravity.

2 Likes