- Home /
Is there a way to edit a static variable
I know a static variable means that the variable is set, but I need the variable to change and still be accessible from another script.
the variable is:
var HEALTH = 0;
I know the static variable is:
static var HEALTH = 0;
I just need the variable to be accessible through another script and at the same time, I need it to be able have different values.
Answer by Jeff-Kesselman · Jun 11, 2014 at 04:07 PM
"I need it to be able have different values."
No. This is the opposite of what a static variable is
http://en.wikipedia.org/wiki/Static_variable
What you are probably looking for is a public variable, Public variables can be accessed by other objects (components.)
In order to do so you need to first find the game object that has the component on it http://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
Then get the component from it: http://answers.unity3d.com/questions/234883/gameobjectgetcomponentscriptenabled-true-not-worki.html
Then access the public using .
You're getting confused between a static variable and a constant. A static variable can have different values - what makes it static is that it's a member variable of a class rather than of an instance of an object.
However, you're correct in saying that static variables are NOT the correct solution to accessing variables from another script.
Answer by LMan · Jun 11, 2014 at 04:14 PM
Static variables are not the best way of accessing variables from other scripts. Have a look at this page from the docs.
Static variables don't belong to any one object- this is why health isn't a good candidate for a static var. Points might be a better example- there will only ever be one instance of it, many scripts access it, and it doesn't really belong to any one object.