increasing a var in one script from another

I want to increase my ammo count when my missles are destoryed
ammoCount is on the launcher script and destory is on the missle script - so I want to increase ammoCount from my missle script

I have got a bit lost but I was trying

Missle.js

var addAmmo:Launcher;

function OnCollisionEnter(collision : Collision) {
..../etc
Destroy (gameObject);
addAmmo.ammoCount + 1;

but it complains about NullReferenceException

Launcher.js

public var ammoCount = 4;

function Update () { 
if (...etc..

    instantiatedProjectile.velocity = transform.forward * speed; 
    ammoCount --;

A couple things that might be happening:

The reference to instantiatedProjectile in your Launcher script might point to null if the instantiatedProjectile has already been destroyed. I can’t tell for sure if this would ever happen, though.

Also, I notice that you’re calling Destroy in your Missile script before you add to your ammo count. This means that the ammoCount line won’t ever get called.

The problem is probably that the missile var addAmmo:Launcher; is set to be something in a scene and then the missile is assigned to a prefab and instantiated. This will break that link. In your missile instantiator you need missile.addAmmo = this;

No. Destroy does not take effect until the next frame.

Change the line in Launcher.js that says

public var ammoCount = 4;

to this:

static var ammoCount = 4;

And rename Missle.js to Missile.js ;), and change it to this:

function OnCollisionEnter(collision : Collision) {
..../etc
Destroy (gameObject);
Launcher.ammoCount ++;

(Get rid of the “var” line and change the “addAmmo.ammoCount + 1;” line.)

–Eric

Sorry for leading you astray, Adam. :sweat_smile:

worked like a dream

Although I forgot to say that static variables have the feature of retaining their value from one run to the next. So you probably want to assign the value of ammoCount in a Start function…just declaring it at the top of the script isn’t enough.

–Eric

works even more like a dream :smile: