0

I am using Unity and C# for the first time, I am atemping to make a 2D platformer game and I am following this tutorial https://www.youtube.com/watch?v=TcranVQUQ5U for the code. I've been following along exactly for everything with the Rigidbody and the code, but when I tested my horizontal movement it didn't work. Here is my code:

using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    private Rigidbody2D body;

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

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

Here is my error:

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

Dylan Kup
  • 9
  • 2
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Yong Shun Jun 25 '21 at 03:35
  • 1
    Make sure that there is actually a `Rigidbody 2D` component on your game object (***not*** `Rigidbody`)? – ph3rin Jun 25 '21 at 03:37
  • 3
    According to the video (11:45), the function name is `Awake`, not `awake`. – Yong Shun Jun 25 '21 at 03:38
  • @dylan-kup remember to have fun with it. This is a great first S.O post so you should have no problems asking more questions if you get stuck. Good luck! – StarshipladDev Jun 25 '21 at 04:02

1 Answers1

4
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    private Rigidbody2D body;

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

    private void Update()
    {
       if(body !=null){
          body.velocity = new Vector2(Input.GetAxis("Horizontal"), body.velocity.y);
       }
       else{
          Debug.Log("body not set to an instance");
       }
    }
}

What is happening in body = GetComponent<Rigidbody2D>(); is the key part.

As @yong-shun said, body is somehow not being set, most likely because awake should be Awake() (unity/C# are case-sensitive ). What this method does is it gets any 'RigidBody2D' components that are attached to the same object as this script. If you have a RigidBody instead of RigidBody2D attached, this script will also fail as there is no RigidBody2D to get and set body as.

If body is set correctly, then the rigidbody of your player can be given a velocity and moved around every update.

If body is not set, an error message will display at the bottom of the preview window instead of throwing an error and crashing.(This is what else{Debug.Log("body not set to an instance"); does)

StarshipladDev
  • 1,166
  • 4
  • 17