NullReferenceException

Hi all,

I’m fairly new to this so forgive my inexperience.

I am trying to create a timer in unity. I have two scripts. The first is the GameControllerScript which creates a variable gameTime = Time.time. This will start when the game is launched. In the levels (or tracks) I want to start a different timer called track time which only begins when the player starts the track so I have a different script for each level.

Here are the two scripts

#pragma strict

public var gameTime : float;

function Start () 
{
	gameTime = Time.time;
}

function Update () 
{

}

and the second one

#pragma strict

private var gameControllerScript : GameControllerScript;
private var trackTime : float;

gameControllerScript = GetComponent(GameControllerScript);

function Start () 
{
	
}

function Update () 
{
	trackTime = Time.time - gameControllerScript.gameTime;
}

This is the error that I am getting.

NullReferenceException: Object reference not set to an instance of an object
TrackControllerScript.Update () (at Assets/TrackControllerScript.js:15)

Please could someone explain why I’m being told that it is a Null reference.

Regards

You can’t set gameControllerScript as a “class” variable [not sure what the correct nomenclature for such a variable is in JavaScript]. You have to do it in a function. in this case I’d recommend Start() :slight_smile:

Add a Debug.Log in Update and print the value of gameControllerScript.

My strong suspicion is that it is null.

If so, check to make sure the object that script is on really has a GameControllerScript component as well.