Unity movement in C#

Good evening People,

I have a applied the following script to my player from the Unity website but keep getting the error NullReferenceException: Object Reference not set to instance of an object and it relates to line 14 in the code: if (controller.isGrounded) { please see below i dont see any issues here, i have checked the internet and i cant seem to find out why this is happening:

using UnityEngine;
using System.Collections;
 
public class PlayerMove : MonoBehaviour {
    //Variables
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F; 
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
 
    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        // is the controller on the ground?
        if (controller.isGrounded) {
            //Feed moveDirection with input.
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            //Multiply it by speed.
            moveDirection *= speed;
            //Jumping
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;
 
        }
        //Applying gravity to the controller
        moveDirection.y -= gravity * Time.deltaTime;
        //Making the character move
        controller.Move(moveDirection * Time.deltaTime);
    }
}

I hope you can help guys :wink:

okay guys figured it out i created the player but had no character controller on it added this and is now moving, one thing though when i press the up arrow it goes backwards and then when i press the back arrow it goes forward strange

you should move

CharacterController controller = GetComponent<CharacterController>();

out of the update function. Lookups need to be avoided as much as possible.

instead, put it in start and declare the variable outside of the function body…

CharacterController controller;
void Start() 
{
controller = GetComponent<CharacterController>();
}

moveDirection = new Vector3(Input.GetAxis(“Vertical”), 0, Input.GetAxis(“Horizontal”));

And just to make sure, you have put a character controller component on the gameobject in question right?

lol. he solved his problem about 3 posts ago santh and elite… reading the thread can help :wink:

yeah, i completely browsed past it, i think i looked at your reply and did not pay any attention :smile: