[Solved] The variable is assigned but its value is never used

This is the first time I’ve written any code, and I’m following a basic tutorial, but I can’t seem to get it to work. I keep getting the error, “The variable ‘movement’ is assigned, but its value is never used.” Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public float acceleration;
    public float maxSpeed;
    private Rigidbody rigidBody;
    private KeyCode[] inputKeys;
    private Vector3[] directionsForKeys;

    void Start() {
        inputKeys = new KeyCode[] { KeyCode.W, KeyCode.A, KeyCode.S, KeyCode.D };
        directionsForKeys = new Vector3[] { Vector3.forward, Vector3.left, Vector3.back, Vector3.right };
        rigidBody = GetComponent<Rigidbody>();
    }

    //1
    void FixedUpdate() {
        for (int i = 0; i < inputKeys.Length; i++) {
            var key = inputKeys[i];

            // 2
            if (Input.GetKey(key)) {
                // 3
                Vector3 movement = directionsForKeys[i] * acceleration * Time.deltaTime;
            }
        }
    }
    void movePlayer(Vector3 movement) {
        if (rigidBody.velocity.magnitude * acceleration > maxSpeed) {
            rigidBody.AddForce(movement * -1);
        } else {
            rigidBody.AddForce(movement);
            movePlayer(movement);
        }
    }
}

Because its exactly what it says is happening you are assigning movment here:

 if (Input.GetKey(key)) {
                // 3
                Vector3 movement = directionsForKeys[i] * acceleration * Time.deltaTime;
            }

But then after that you never use it.

Note that the movement in FixedUpdate is a local variable you declare it in FixedUpdate and assign it there.

The movement variable in MovePlayer is also a local variable. Which means its a totally different variable than FixedUpdate’s movement variable even though they have the same name. Its like labeling a shelf in the living room movement… Then going into a bedroom and labeling a shelf there movement. They can hold different things, and one has nothing to do with the other… even though they have the same name.

Secondly, and the reason your code isn’t working , is you never call MovePlayer, so its never run. Just add this code to the end of your FixedUpdate.

 void FixedUpdate() {
        for (int i = 0; i < inputKeys.Length; i++) {
            var key = inputKeys[i];
            // 2
            if (Input.GetKey(key)) {
                // 3
                Vector3 movement = directionsForKeys[i] * acceleration * Time.deltaTime;
                //  New Code Here <---------------------
                 MovePlayer(movement);
            }
        }
       
    }

This passes the Vector3 movement in FixedUpdate down to the MovePlayer method.

Yay! It works now. Thanks so much for the detailed response! :slight_smile: