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.)