I’m trying to move the ball with the player controller script, at the Environment and Player tutorial with the code exactly as written, but with an extra snippet to see if the script is getting the rigidbody component, and VS shows no errors. When I start the game, the ball will not move with either the arrow keys or wasd, and at the line that adds force to the rigidbody, rb.AddForce (movement * speed); , I keep getting an error that says NullReferenceException: Object reference not set to an instance of an object. I’ve seen this question asked many times, but never answered. Here is the code I’m using, and there’s no typos.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float speed = 10.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
if (rb = null)
{
Debug.Log("There is no rigidbody in " + transform.name);
}
else
Debug.Log("Rigidbody component from gameobject is aquired.");
}
}