- Home /
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
Answer by fafase · Jun 25, 2014 at 06:06 AM
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.
Counter.js
static var counter:int = 0;
// GUI stuff using counter
OtherObject.js
function OnTriggerEnter (){
Counter.counter++ ;
Destroy(gameObject);
}
why
Counter.counter++ ;
because that doesnt seem to work
counter is static, so it is called via the Counter class (Note that I changed the first letter for a lower case). ++ to increase it by one.
Also, this is all depending on your script names. I do not know what are the na$$anonymous$$g you are using, you need to change it if your class is named different.
its now co$$anonymous$$g up with the error:
Operator '++' cannot be used with an expression of type 'Object'
Your answer
Follow this Question
Related Questions
How to define component properties globally 1 Answer
Embed icons in GUI text?? 1 Answer
Output text GUI not working 2 Answers
Camera following a moving object 0 Answers