Null Refference Exception: object reference not set to an instance of an object

Okay, so I have this script,

function Update () {
 
var controller : CharacterController = GetComponent(CharacterController);
 
if (!controller.isGrounded)
 
animation.CrossFade ("Walk");
 
else
 
animation.CrossFade ("Jump"); }

and I keep getting the Null Refference Exception error. It’s supposed to make my character play the walk animation when grounded and when not grounded play the jump animation. This script have been giving me a heap of trouble! Thanks for reading!

-Rov

Make sure you have a CharacterController component and an Animation component on the same GameObject than this script.

Anyway, it is always better to perform some check inside the script:

function Update () {

    var controller : CharacterController = GetComponent(CharacterController);
    if (!controller || !animation)
        return;

    if (!controller.isGrounded) {
        animation.CrossFade ("Walk");
    }
    else {
        animation.CrossFade ("Jump");
    }
}

You can also enforce the presence of the CharacterController component with the RequireComponent attribute.

@script RequireComponent(CharacterController)

And for performance purpose, you can cache the CharacterController component, once and for all:

var controller : CharacterController;

function Awake()
{
    controller = GetComponent(CharacterController);
}