- Home /
GameObject variable change for all of the objects
I know this is much to read but thanks for any help
There is 2-5 instantiated prefabs, they all have the same script named 'walk' and they all have a variable named stage, i made a for loop to respawn the prefabs(just a random number every time). in the loop i have another random variable called randomX which responsible for the x position in the screen of the prefab. anyways if the its spawns on the left side of the screen i want the prefab to move to the right side by changing the stage variable(string) to "ltr" and if its spawns on the right side of the screen i want the prefab to move to the left side by changing it to "rtl",this works but the problem is that its changing for all of the prefabs and not just to to the current prefab.
Spawn script:
for(var k : int = 0; k < respawnNum; k++){
var yRandomPos : float = Random.Range(6.98,-4.8);
xRandomPos = Random.Range(14.0, -14.0);
var position2: Vector3 = Vector3(xRandomPos, yRandomPos, -3.980108);
var pref2 : GameObject = Instantiate(prefab, position2, Quaternion.identity);
if(xRandomPos < 0){
pref2.GetComponent(walk).state = "ltr";
}
else if(xRandomPos >= 0){
pref2.GetComponent(walk).state = "rtl";
}
Walk script:(every instantiated prefab has this script)
function Update(){
if(this.state == "ltr")
transform.position.x += finalSpeed * Time.deltaTime;
else if(this.state == "rtl") transform.position.x -= finalSpeed * Time.deltaTime;
}
finalSpeed is just a variable.
Are you using a static variable? If so, don't. (Also, you should really use an enum for the state, rather than using strings, which are more prone to user error and won't generate compiler errors if you mess them up.)
I dont have any errors, and yes i do use static variable to access it from other script, and i dont really know how to use enum good. if you can explain to me and also if you can to show me with my code. again if you didn't understood my problem: the variable changes for all the gameObject who have the script and not just to the current gameObject
Answer by NoseKills · Jan 19, 2015 at 08:56 PM
and yes i do use static variable to access it from other script
A variable only has to be declared "public" to be accessible from other classes, not "static". "Static" means the variable is defined for that class, not independently to each instance of the class. So if "state" is declared static, it does change everywhere no matter where you change it.
Ok, i didn't really knew this so thank you very much
Your answer
Follow this Question
Related Questions
How would I be able to subtract from a variable when it hits something? (OnCollisionEnter) 1 Answer
Acces to a var from another Script. 2 Answers
Lottery system 1 Answer
How do I change the text of a GUIText object through another GameObject using a variable? 2 Answers
Scripts accessing one another (JS) 0 Answers