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:
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?
asked Apr 02 '11 at 08:28 PM
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.
answered Apr 02 '11 at 08:51 PM
I think you need to add "" to this line:
hopefully this helps but not totally sure
answered Apr 02 '11 at 08:39 PM