Error: The name 'velocity' does not exist in the current context

I am pretty new to Unity and Scripting and I got an error while trying to add the jumping mechanic and I can’t figure out how to fix it.

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] Transform playerCamera = null;
    [SerializeField] float mouseSensitivity = 3.5f;
    [SerializeField] float walkSpeed = 6.0f;
    [SerializeField] float gravity = -13.0f;
    [SerializeField][Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
    [SerializeField][Range(0.0f, 0.5f)] float mouseSmoothTime = 0.03f;

    [SerializeField] private float jumpHight = 1.5f;

    [SerializeField] bool lockCursor = true;

    float cameraPitch = 0.0f;
    float velocityY = 0.0f;
    CharacterController controller = null;

    Vector2 currentDir = Vector2.zero;
    Vector2 currentDirVelocity = Vector2.zero;

    Vector2 currentMouseDelta = Vector2.zero;
    Vector2 currentMouseDeltaVelocity = Vector2.zero;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        if (lockCursor)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
       
    }

    // Update is called once per frame
    void Update()
    {
        UpdateMouseLook();
        UpdateMovement();

        if (Input.GetKeyDown("space"))
        {
            print("Player Has Jumped!" +
                "I think..." +
                "Listen! i'm a text box and text boxes don't have eyes!");
        }
    }
   
    void UpdateMouseLook()
    {
        Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

        currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);

        cameraPitch -= currentMouseDelta.y * mouseSensitivity;
        cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);

        playerCamera.localEulerAngles = Vector3.right * cameraPitch;
        transform.Rotate(Vector3.up * currentMouseDelta.x  * mouseSensitivity);
    }

    void UpdateMovement()
    {
        Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        targetDir.Normalize();

        currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);

        if (controller.isGrounded)
            velocityY = 0.0f;

        velocityY += gravity * Time.deltaTime;

        Vector3 velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;

        controller.Move(velocity * Time.deltaTime);

//ERROR IS HERE
//ERROR IS HERE
            if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }

    }

    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHight * -2 * gravity);
    }
}

The error should be in line 94 of the code you posted, not the lines you marked. You declared the velocity variable inside your UpdateMovement method in line 79 (of your posted code). So that variable only exists inside this method. So inside your Jump method there is no variable available that is called velocity. Since you seperated out the Y component, you may wanted to use “velocityY” inside Jump?

1 Like

to fix this just declare your Velocity varible outside of the updateMovement method then you will be able to reference it in any of the methods

private Vector3 velocity;
    void UpdateMovement()
    {
        Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        targetDir.Normalize();
        currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
        if (controller.isGrounded)
            velocityY = 0.0f;
        velocityY += gravity * Time.deltaTime;
         velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;
        controller.Move(velocity * Time.deltaTime);
//ERROR IS HERE
//ERROR IS HERE
            if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }
    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHight * -2 * gravity);
    }

this got rid of the error but the jumping mechanic still does not work, Thanks anyways!

this got rid of the error but the jumping mechanic still does not work like the other post, Thanks anyways!

I only addressed your syntax error. Any logical errors belong to yourself ^^. You should think about what is executed in which order. You have your “jump” detection at the very any of your method. So it’s the last thing that is happening in a frame. So when you press jump you set the Y velocity to the jump force in order to jump up. However look what’s happening the next frame. You have this before all of your movement code:

        if (controller.isGrounded)
            velocityY = 0.0f;

So of course since you’re still on the ground you just eliminate the velocity you just set at the end of the last frame. So this doesn’t make much sense logically.

Are you looking to learn programming by making a character controller, or do you just want a functioning character controller so you can do other stuff? There’s plenty of those you can start from, such as this one:

https://discussions.unity.com/t/855344

That prototype one has run, walk, jump, slide, crouch… it’s crazy-nutty!!

If you want to fix your code:

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

Yeah actually that makes sense