"NullReferenceException" error?


so I keep getting this error:

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


using UnityEngine;
using System.Collections;

[RequireComponent(typeof(PlayerPhysics))]   //because we will need the physics
public class PlayerController : MonoBehaviour {

	//player handling
	public float speed = 8;
	public float acceleration = 12;

	private float currentSpeed;
	private float targetSpeed;
	private Vector2 amountToMove;

	private PlayerPhysics playerPhysics;

	// Use this for initialization
	void Start () {
		playerPhysics = GetComponent<PlayerPhysics> ();
	// Update is called once per frame
	void Update () {
		targetSpeed = Input.GetAxisRaw ("Horizontal") * speed; //Returns the value of the virtual axis identified by axisName with no smoothing filtering applied.
		currentSpeed = IncrementTowards (currentSpeed, targetSpeed, acceleration);

		amountToMove = new Vector2(currentSpeed,0);
		playerPhysics.Move(amountToMove * Time.deltaTime);

	private float IncrementTowards (float n, float target, float a){
			if (n == target) { //if the current speed is already equal to the target speed, return current speed
				return n;	
			else{ //otherwise, we first want to see in which direction must the current speed be incremented to get the target, must it be a negative or a positive?
			float dir = Mathf.Sign(target - n); //must be increased or decreased to get closer to target
			n += a * Time.deltaTime * dir; //incrementing current speed
			return (dir == Mathf.Sign(target-n))? n: target; //if n has now passed target then return target, otherwise return n

What is wrong with it??


playerPhysics = GetComponent ();

didn’t get the Component you’re looking for.

Make sure your PlayerPhysics component is attached to your gameObject… to do that, your PlayerPhysics should inherit from MonoBehaviour.

Also, try re-adding your current script to your gameObject. The [RequireComponent (typeof(PlayerPhysics))] doesn’t kick in instantly when you put it in your script.