Can't access public variables from a script on a different object

I have 2 objects, a gun and an ammo counter. The gun object has a public variable called "ammo" with a value of 10. On the ammo counter, I have this script:

var gunObject:GameObject;
gunObject = GameObject.Find("gun");

var ammo = gunObject.GetComponent(gunScript).ammo;

function Update () {
    guiText.text = "Ammo " + ammo;
}

This, however, doesn't seem to want to work. It always gives me an error saying

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

Anybody know what could be going wrong?

Put the "gunObject = GameObject.Find("gun");" line inside a Start function. Only declare variables outside functions, never put any code that "does stuff" outside. The "var ammo = gunObject.GetComponent(gunScript).ammo;" line should be inside Update. Otherwise it would be set once and would never change.

Actually, the best way is not to use Update anyway. Just change the guiText.text when the ammo actually changes, that way you won't waste CPU cycles checking every frame for no reason. So you'd want to get a reference to the GUIText object from your ammo script, instead of the other way around.

I think you need to add "" to this line:

var ammo = gunObject.GetComponent(gunScript).ammo;

should be

var ammo = gunObject.GetComponent("gunScript").ammo;

hopefully this helps but not totally sure

Scribe