Static Variable Headache

Hi,
I’m very new to unity. I’m trying to write a script using global variables to increment the score by 1 when an object is hit. I have a script called GlobalVars.js that looks like the following:

#pragma strict

static var ScoreCounter : int = 0;

I then have a script called guiscript.js that monodevelop recognises GlobalVars in and I get “Score: 0” at the top of the screen. That looks like the following

#pragma strict


function OnGUI(){

GUI.Label(Rect(10, 10, 100, 20), "Score: " + GlobalVars.ScoreCounter);

}

However when I try to use this script (Oncollisionball.js), I get an error that I will post below:

#pragma strict

function Start(){

print("working start");

}
function OnCollisionEnter (collision : Collision) {

	if(collision.gameObject.tag == "Enemy")
	{	
		Destroy(collision.gameObject);
		Destroy(gameObject);
		print("working collision");
		GlobalVars.ScoreCounter +=1;
	}
}

Error:
Assets/Standard Assets/Character Controllers/Oncollisionball.js(15,17): BCE0005: Unknown identifier: ‘GlobalVars’.

Thanks for your time,
Dan

Have you tried moving the Oncollisionball script out of Standard Assets?

I don’t use Javascript much (C# all the way for me) but try:
public static var ScoreCounter : int = 0;

Edit: Actually what the guy above said makes a bit of sense. Some bits of code get compiled before others.
There are some folders that are “special cases” so it’s always best to set up your own project structure rather than bolting onto what is given to you.

No, the way he declared it is right. Putting public in front of it would just be redundant.

Thanks a lot. Moving the script out of Standard Assets did the trick!

Awesome!

I think standard assets get compiled first, so they can’t reference anything outside of them. (could be wrong though)

instead of using static vars, use normal default vars, because static vars can cause some game logic bugs, such as your health not reseting to 0, after a game reload,

try this instead :

private var TheBall : Transform;

function Start()
{
    TheBall = GameObject.Find("Ball").GetComponent("MoveAroundScript");
}

function Update()
{
    if(IveDoneSomethingHere)
    {
         TheBall.enabled = false;
    }
    else
    {
         TheBall.BallMoveSpeedVar = Mathf.Infinity;
         //LOL Infinity :)
    }
}

by using GameObject.Find(“Name”).GetComponent(“Script”).function/variable/action/boolean; You then dont ever will need to use static, but make sure the vars arent private either, they will have to access it!

The main advantage of static vars is that they’re incredibly easy to port between scenes, and to hold stuff like score, points, loadouts, or stuff you don’t want to reset, like options. And resetting them is merely a matter of recording them at the beginning of a scene, and resetting it at the end. They’re not necessary, but they help clean up spaghetti code.

yes i know ^^^, i use them also a lot, but then… nvm