My static variable is not changing

I’m just trying a simple test to get my static variable to change. I believe static variables are global variables and should be changeable from other scripts but it’s not working out for me.

In one object I have a script that sets up the variable.

static var score: int = 0;

And in a different object and script I try to reference it.

var SCORE :int = GetComponent(S_Player).score;


function OnTriggerEnter(other: Collider){

if (other.gameObject.tag == “Fish”){

  	other.transform.position.y = 8;
  	other.transform.position.x = Random.Range(-7,7); 

     //check if  asset is there... 		

                  if (P_Death){

  	Instantiate(P_Death,transform.position,transform.rotation);		
  	SCORE+=1; 			
                  Debug.Log("Works");
  	} 		
                 Destroy(gameObject);	 	}

}

Sorry the code looks crummy the blockcode doesn’t seem to like formatting.
Anyway, when I hit an object I should add 1 to my score. Well, when I run the function and I hit the object everything works but the adding the score part. I don’t get any errors, and my score doesn’t change. My debug log works so my function is working. So I’m guessing this is a logic problem so what did I do wrong? Is it just poor referencing and if so what is a better method? So yes, my whole function works, I have no errors messages but I’m not adding to my score.

2 Answers

2

When you set an integer equal to another integer like that it does a copy by value so your integer score is equivalent to SCORE when you initialize it, but they point to different locations in memory so changes in one won’t be seen in the other. If you want to change a simple static int like that and have your changes get reflected everywhere you either need to change that specific variable (S_Player.score) or you’ll need to wrap it in a class.

It looks as though you are attempting to use the variable as a public and not a static though. You could access your static variable by simply using S_Player.score, you don’t need to find the specific component of that class you have since a static variable is shared across all instances of that class. Your code the way it is written now would still compile and run if you made the variable in question public instead of static, of course it would have the same outcome as before because of the issues I outlined in the first paragraph.

So my GetComponent(S_Player).score; is pretty useless then? Awe. I thought it allowed me to change the variable, but it basically just gives me a copy right?

I don’t understand exactly what you said, what would be the right class to use if I want to change that specific variable through different scripts?

Could I just make my variable a public static variable so there is only one variable used by all instances?