Keeping count of cubes left on screen

I’m working on a simple physics game prototype as my first project in Unity, and I’ve come across a problem.

There’s an empty game object with a script attached to it that is supposed to keep track of how many cubes are left.

Here’s that script…

#pragma strict

public var cubesLeft = 1;

function Update () {

  if (cubesLeft == 0) {		
  	  print("no cubes");
  }
}

So, in another script, when the box is destroyed, I’m trying to take one away from cubesLeft.

Here’s that script…

#pragma strict

function OnCollisionEnter(collision:Collision) {
      var codeFile:code;
     	   codeFile = gameObject.GetComponent("code");

   if(collision.gameObject.tag == "Finish") {
	   Destroy(gameObject);
	   codeFile.cubesLeft = codeFile.cubesLeft - 1;
	
   }
 }

However, I’m getting this error when the collision happens…

NullReferenceException: Object reference not set to an instance of an object
cubes.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/cubes.js:14)

From what I’ve read, it seems like cubesLeft is null in the second script, but I can’t find out how to get it to read the value from the first script.

Thanks in advance for your help!

So you are using GetComponent, but that gets a component (a script) on the current game object not on your empty game object.

You need to do this

var codeFile = GameObject.Find("NameOfTheGameObject").GetComponent(NameOfTheScriptWithoutQuotes);

There is another way:

Make public var cubesLeft a static like this:

  public static var cubesLeft = 1;

Now it has just one value everywhere and you can access it from anywhere like this:

  NameOfYourScript.cubesLeft--; //Or whatever