NullReferenceException when trying to animate sprite

Hello,

I have been trying to animate a sprite. I have some animations set up, added an animation controller to my object and configured the controller in the animator tab, but when I try to change the value of my State Parameter, the following error shows:

NullReferenceException: Object reference not set to an instance of an object

Here is the code where I am trying to change the animation:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	Animator animator;

	public KeyCode left;
	public KeyCode right;

	// Use this for initialization
	void Start () {
	}

	void FixedUpdate () {
		if (Input.GetKey (left)) {
			animator.SetInteger ("State", 2);
		}
		if (Input.GetKey (right)) {
			animator.SetInteger ("State", 2);
		}
	}
}

I am trying to change the value of State to 2, which should trigger the transition to my “run” animation.

The Animator animator; variable is never being set, so it’s staying at its default value of null, and when a method is called on null it results in a NullReferenceException. Try putting this in the Start() method to set the variable to the Animator attached to the same GameObject:

animator = GetComponent<Animator>();