- Home /
Error "There is already a local variable with the name 'obstacle'." How can I make it work?
Hello. This is the part of my script Unity hates. I can't assign "obstacle" more than one time. How can I fix this and let it work? Thank you!
if(whichToSpawn == 0){
var obstacle = Ob_1;
}
else if(whichToSpawn == 1){
var obstacle = Ob_1;
}
else if(whichToSpawn == 2){
var obstacle = Ob_3;
}
Answer by Eric5h5 · Feb 05, 2011 at 06:49 PM
Take off the declarations for the other two variables.
Thank you, I actually did that just after I pushed publish question. Except I had to take off all 3. :D It works now!
@$$anonymous$$eavon, js creates a global variable if you don't include the 'var' identifier.
@Peter G: that's not the case...'var' is just optional; nothing different happens if you use it or not.
Hmm, I did not know that. Could you maybe explain what this tread is saying then...http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript
@Peter G: That's web Javascript; who cares about that? It's not relevant to Unity.
Answer by Mai hime · Feb 05, 2011 at 06:56 PM
you have to create the variable obstacle once :
var obstacle=Ob_1;
if(whichToSpawn == 0){
obstacle = Ob_1;
}
else if(whichToSpawn == 1){
obstacle = Ob_1;
}
else if(whichToSpawn == 2){
obstacle = Ob_3;
}
In JS, because of the way it handles scope, you don't have to declare the variable ahead of time, you can just declare it for the first one.
even if it's after an if statment ?? i mean if the condition is false the code block inside if will not be executed
Yes, even if it's after an if statement. It doesn't matter if the code is executed or not; JS handles scope differently than C#.
Your answer
Follow this Question
Related Questions
Unity Giving Errors after adding "Private" 1 Answer
What is the problem with this code? 1 Answer
Editing the jumppad from the 3rd person tutorial 2 Answers
I'm wondering with if function working 2 Answers
Save data not creating save file 1 Answer