Hi i am new to unity i am trying to make movement with the character controller but when i press play i get an error

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

public class PlayerMovement : MonoBehaviour
{
    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    private float playerSpeed = 2.0f;
    private float jumpHeight = 1.0f;
    private float gravityValue = -9.81f;

    private void Start()
    {
        controller = gameObject.AddComponent<CharacterController>();
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        controller.Move(move * Time.deltaTime * playerSpeed);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }

        // Changes the height position of the player..
        if (Input.GetButtonDown("Jump") && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}

This is the error: NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Script/PlayerMovement.cs:21)

Well it looks like you dont have a reference to the controller variable set properly but first edit your question to include the code as well thats the 101010 thing at the top of the edit bar with the quotes and others.

Hey I believe there been a miscommunication so you need to put the code that you wrote in VS here with the error. And also set the code editor correctly in unity properly. You do that by going to Edit -> preferences -> external tools -> external script editors ->

3 Answers

3

Your script doesn’t seem to have any problem just tried it on an empty scene with a capsule works like a charm.

Thats weird, well anyways thanks for the help

Maybe its a different script causing the error?

It couldve been that but it is the only script i have