0

I followed a tutorial for a simple 2d character controller, here is the code:

using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;

private void awake()
{
    body = GetComponent<Rigidbody2D>();
}

private void Update()
{
    body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
}

}

I get this error every frame (the update function):

NullReferenceException: Object reference not set to an instance of an object PlayerMovement.Update () (at Assets/scripts/PlayerMovement.cs:15)

The error its at line 15, where is the "body.velocity" thing, Anyone knows where is the problem?

NASA BOI
  • 25
  • 3

1 Answers1

2

Most likely, body is null, because the component it's referencing has not been defined. You have to attach a Rigidbody2D component to the Game Object that your script is sitting on.


Since this script requires a Rigidbody2D to work, you can add a line that will automatically create it on the Game Object when your script is added. It goes at the top of the class definition, like so:

[RequireComponent(typeof(Rigidbody2D))] // <- This is what I'm talking about.
public class PlayerMovement : MonoBehaviour
{
    // To save space, I didn't paste the rest of your code.
    // ...
}

View official documentation on RequireComponent[].

When you add a script which uses RequireComponent to a GameObject, the required component will automatically be added to the GameObject. Note that RequireComponent only checks for missing dependencies during the moment the component is added to the GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies added automatically.


Alternatively, you can remove the code inside your Awake() method that fetches the component, and instead drag-and-drop the component in the inspector.

This is the recommended way to do things, because it makes your script more flexible: you won't have to rewrite it when there comes a time that the Rigidbody2D component needs to be attached to a different Game Object than your PlayerMovement. (This will happen surprisingly often.)

verified_tinker
  • 625
  • 5
  • 17