- Home /
Question by
Wyko · Jun 25, 2011 at 12:08 AM ·
switchlocalswitch-case
Variable usage in Switch Statements
Why does the following code throw: There is already a local variable with the name 'wall'
? They are all in different parts of the switch, so shouldn't the variable be unique?
switch (type){
case 0 :
var tile : Transform = Instantiate(tilePrefab.transform, new Vector3(x,0,z),Quaternion.identity);
tile.name = TileArray[x, z].Name();
break;
case 1 :
var wall : Transform = Instantiate(wallPrefab.transform, new Vector3(x,0.6,z),Quaternion.identity);
wall.name = TileArray[x, z].Name();
break;
case 2 :
var wall : Transform = Instantiate(wallPrefab.transform, new Vector3(x,0.6,z),Quaternion.identity);
wall.name = TileArray[x, z].Name();
break;
}
Comment
You can create scope using { }
case 1:
{
// some code here
break;
}
You'd probably be better off using arrays anyway:
var tilePrefabs : Transform[];
...
var tile : Transform = Instantiate (tilePrefab[type], new Vector3(x,0,z),Quaternion.identity);
tile.name = TileArray[x, z].Name();
Then you don't need switch/case at all.
Answer by ckfinite · Jun 25, 2011 at 12:17 AM
No. The parts of a switch statement are not like the body of a if statement or a loop, i.e. they don't have their own scope. Anyway, it isn't really good variable naming practice to reuse the same name.
Answer by Grim_Darknight · Apr 30, 2013 at 11:46 PM
The reason it tells you you already have one is because of the double declaration. Define your variable outside the switch statement once then use it.
Your answer
