SpaceMarine Movement Error - Character Controller

Hello,

I implemented the Character Controller movement procedure in Chapter 4 for the SpaceMarine game object, and I received the following error:

NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:19)

The script is as follows:

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

public class PlayerController : MonoBehaviour
{
public float moveSpeed = 50.0f;
private CharacterController characterController;
// Start is called before the first frame update
void Start()
{
var characterController = GetComponent();
}

// Update is called once per frame
void Update()
{
    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    characterController.SimpleMove(moveDirection * moveSpeed);
}

}

I attached this script to the SpaceMarine GameObject, and I have been successful in implementation up to to this point.

Other Information:
The Space Marine is a prefab and an instantiated GameObject in the hierarchy.
It inherits the parent MonoBehaviour transform component.
It implements a Character Controller.
It has a C# script attached named PlayerController.cs, which runs the script as it appears above.

Please let me know if there is anything you notice that I am doing wrong.

Here is a screenshot for the virtual sleuths.
ScreenShot%20Unity%20Practice

@bdmoakley Can you please help with this when you get a chance? Thank you - much appreciated! :]

It looks like the script can’t find your character controller. That’s where the null is coming from. The problem is in Start(), you are overriding your instance variable with a local variable. Also you are calling GetComponent without stating what kind of component you are getting. The line should be:

characterController = GetComponent<CharacterController>();

I hope that helps.

This topic was automatically closed after 166 days. New replies are no longer allowed.