Reputation: 19
Today I started my adventure with unity and I wanted to make an object move forward when you press "w". Surprisingly it does not work, error pops up. I literally copied the code from tutorial, and yes I have added code as a component of an object. Bellow the code and error message:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
public float Force = 2000f;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
rb.AddForce(0, 0, Force * Time.deltaTime );
}
}
}
Error message: NullReferenceException: Object reference not set to an instance of an object PlayerMovement.FixedUpdate () (at Assets/PlayerMovement.cs:14).
Upvotes: 0
Views: 117
Reputation: 2316
Core problem and initial solution
Rigidbody is not automatically grabbed by scripts. You must call GetComponent and assign the Rigidbody to the field in order to use it. Typically this is done in the Awake method:
void Awake()
{
rb = GetComponent<Rigidbody>();
}
Alternative:
You could also expose your rb field in the inspector by marking it public, or adding the [SerializeField] attribute. Then you can drag the Rigidbody component into the slot in the inspector:
[SerializeField] private Rigidbody rb;
Upvotes: 3