Global Variable help

I am trying to get a UI counter to work off a global variable since there are several items that will be connected to this script.

I need it to add one to the counter every time one of the items is destroyed.

So far my UI script looks like this (it is very messy, I know)

static var Counter : int = 0;

 guiText.text = " " +Counter;

and this is the code for thr items so that they get destroyed and my attempt to add a global variable to it.

static var Counter : int = 0;

function OnTriggerEnter (){
Counter = Counter + 1 ;
Destroy(gameObject); //Destroys the object the script is attached to.

what do I need to do to make this work

This is a case of reviewing what s static and instance member. Static belongs to the class and not the object, so when you destroy the object and the component attached to it, the static variable remains in memory with the given value.

So you could go with two scripts.


static var counter:int = 0;
// GUI stuff using counter


function OnTriggerEnter (){
    Counter.counter++ ;