- Home /
Changing a variable in another script for one object.
Ok, I already know how to change the variable in another script. All you do is this:
GameObject.GetComponent(ScriptName).variableName +=1;
But my problem is I have to change the variable TestVariable located in one Gameobject, even though the script is in many gameobjects.
That Probably didn't make sense, so let me explain.
I have hundreds of game objects stored in a 3-dimensional array called "chunks", like this:
static internal var chunks : GameObject[,,] = new GameObject[5,5,5];
for(var z=0;z<chunktotal;z+=1) {
for(var y=0;y<chunktotal;y+=1) {
for(var a=0;a<chunktotal;a+=1) {
chunks[x,y,z]=GameObject.Instantiate(chunkObject,Vector3(x,y,z),Quaternion.identity);
This creates 125 of the object "chunkObject". "chunkObject" is a GameObject that has the component "ScriptA" in it. So now lets say I want to change a variable in the script of of just one of the 125 gameobjects I created. Here is how Im currently doing it:
chunks[0,0,0].GetComponent(ScriptA).testvar =1;
This code works. Except for one problem. Every single testvar in the objects stored in chunks[x,y,z] is changed. For example, running the code above would change all 125 gameobjects have testvar set to 1. Even though I specified which one I wanted to change! (In this case, chunks[0,0,0])
So does anyone know how to edit this code to change testvar of just one gameobject, not all 125?
Answer by ebogguess · Jul 04, 2013 at 03:35 AM
I can't see the code that defines testvar, but I would wager that you've defined it as static. When you change a static variable, any instances that can see that variable will be updated as well.
Yup, testvar is in fact static. I finally understand why this was happening!
now that I know how static variables work, Im going to edit my project further to see if I can solve it. ill post any problems or solutions I find. Until then...
Finished!!!!! makeing testvar a static variables was the only problem. All I had to do was take it away, make testvar non-static.
Answer by JiffyJuff · Jul 04, 2013 at 03:09 AM
You make a boolean. Then you set this variable of the target object to true in the inspector. Then you test if it is true. If so, chang testvar to 1.
unfortunatly, The inspecter is out of the option because I create the objects during gameplay.
Your answer
Follow this Question
Related Questions
enable/disable script from another script c#? 2 Answers
Calling a function in another script. 1 Answer
change variable in script attached to parent using triggers 1 Answer
Random Compiler error 1 Answer
Tree Chopping Script Issues 2 Answers