Sprinting Script Issue

Hi everyone,

I have an issue with my script, where I want the character to be able to move faster when a button is pressed. The script I wrote is based off a tutorial from brackeys (Sprinting - Unity Tutorial - YouTube). I have no idea why I’m getting the following error:

NullReferenceException: Object reference not set to an instance of an object
Sprinting.Update () (at Assets/Scripts/Sprinting.js:31)

This is my script I’ve written in JavaScript. I think this could be a compatibility issue as the tutorial was written in Unity 3 and I am using Unity 4.

#pragma strict

var walkSpeed : float = 7; // Regular speed
var sprintSpeed : float = 13; // Run speed
private var charMotor : CharacterMotor;
private var charController : CharacterController;

function Start () 
{
	charMotor = GetComponent(CharacterMotor);
	charController = GetComponent(CharacterController);
}

function Update () 
{
	//Making the actual speed var
	var speed = walkSpeed;
	
	//Checking for oppertunity to sprint
	if ( charController.isGrounded && Input.GetKey("left shift"))
	{
		//changing the speed to sprint
		speed = sprintSpeed;
	}
	
	charMotor.movement.maxForwardSpeed = speed; //Setting the speed
}

Thanks a lot for your help guys!

Be sure that the script is attached to your character. Be sure your character has a CharacterController component, AND the CharacterMotor component attached, which both come with the asset package. That seems to be the problem, because if you check for the components, you can see if they are null or not. Try this and see what you get in the console.

#pragma strict

var walkSpeed : float = 7; // Regular speed
var sprintSpeed : float = 13; // Run speed
private var charMotor : CharacterMotor;
private var charController : CharacterController;

function Start () 
{
	charMotor = GetComponent(CharacterMotor);
	charController = GetComponent(CharacterController);
}

function Update () 
{
	//Making the actual speed var
	var speed = walkSpeed;
	
	//Checking for oppertunity to sprint
	if(charController != null)
	{
		if ( charController.isGrounded && Input.GetKey("left shift"))
		{
			//changing the speed to sprint
			speed = sprintSpeed;
		}
	}
	else print("charController component not found.");
	
	if(charMotor != null)
		charMotor.movement.maxForwardSpeed = speed; //Setting the speed
	else print("charMotor component not found.");
}