NullReferenceException: Object reference not set to an instance of an object PlayerController.Update

using UnityEngine;

[ RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{

[SerializeField]
private float speed = 5f;

private PlayerMotor motor;

void start ()
{
motor = GetComponent();
}

void Update ()
{

float _xMov = Input.GetAxisRaw(“Horizontal”);
float _zMov = Input.GetAxisRaw(“Vertical”);

Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;

// final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;

//Apply movement
motor.Move(_velocity);

}

}

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

This should be void Start()
Capitalisation matters, otherwise this method will not be run by the engine automatically (and therefore nothing will get assigned to your motor variable causing it to be null).

And next time you post a script put it in code tags (there is a sticky guideline topic that tells you how to do this).

1 Like