Can C# have local variables with the same name?

I’ve been following a tutorial that is in C# and converting it to javascript. There’s a section of the script that gives errors in javascript, for good reason! In the C# script the variables x, y, and z are declared twice in separate loop statements. I don’t know why that would work. It sure doesn’t work in javascript! I put an underscore before the second set of duplicate variables but my script didn’t work. I’m not sure if its because the variables need to be the same or not. Here’s the section from script in the tutorial:

void Start () { data = new byte[worldX,worldY,worldZ]; 
for (int x=0; x<worldX; x++)
{
for (int z=0; z<worldZ; z++)
{
int stone=PerlinNoise(x,0,z,10,3,1.2f);
stone+= PerlinNoise(x,300,z,20,4,0)+10;
int dirt=PerlinNoise(x,100,z,50,3,0)+1;
for (int y=0; y<worldY; y++)
{
if(y<=stone)
{
data[x,y,z]=1;
} 
else if(y<=dirt+stone)
{
data[x,y,z]=2;
}
}
}
}
chunks=new GameObject[Mathf.FloorToInt(worldX/chunkSize),Mathf.FloorToInt(worldY/chunkSize),Mathf.FloorToInt(worldZ/chunkSize)];
for (int x=0; x<chunks.GetLength(0); x++)
{
for (int y=0; y<chunks.GetLength(1); y++)
{
for (int z=0; z<chunks.GetLength(2); z++)
{
chunks[x,y,z]= Instantiate(chunk,new Vector3(x*chunkSize,y*chunkSize,z*chunkSize),new Quaternion(0,0,0,0)) as GameObject;
Chunk newChunkScript= chunks[x,y,z].GetComponent(\"Chunk\") as Chunk;
newChunkScript.worldGO=gameObject;
newChunkScript.chunkSize=chunkSize;
newChunkScript.chunkX=x*chunkSize;
newChunkScript.chunkY=y*chunkSize;
newChunkScript.chunkZ=z*chunkSize;
}
}
}
}

C# uses scope differently than JS. Scope is one of the things that Unityscript actually has in common with web Javascript.

–Eric

So how do you suggest I handle this problem?

In C#, the integer ‘x’ only exists inside the for loop. Once the loop is over, there is no such thing as x anymore. So we have to create a new ‘x’ for every for loop.

If I get this right, in UnityScript ‘x’ continues to exist after the for loop. So you just need to reset it, not make another variable ‘x’

After you declare x, y, and z the first time, just reset their values in following loops. By taking out “int” we are no longer declaring a new ‘x’ but changing the value of a previously existing ‘x’.

// The FIRST time:
for (int x = 0; ...; ...)
// Anytime after that
for (x = 0; ...; ...)

Thanks, it works now but my script(which is creating a voxel terrain same as minecraft) only creates one chunk. I’m not sure what its related to

nevermind, my variable was set to only make one. everything works perfectly! :slight_smile:

1 Like