I have this code snippet and am looking to make it cleaner (this is c# for unity btw):
for (int i = 0; i < 4; i )
{
wallObjs[i] = transform.GetChild(i 1).GetComponent<WallObj>();
}
wallObjs[0].setWallState((int)roomData.entryInfo.x);
wallObjs[1].setWallState((int)roomData.entryInfo.y);
wallObjs[2].setWallState((int)roomData.entryInfo.z);
wallObjs[3].setWallState((int)roomData.entryInfo.w);
foreach (WallObj wall in wallObjs)
{
wall.adjacents(roomData.dunGrid, roomData.abstRoom);
}
Preferably, I want it to look something like:
WallObj[] wallObjs = new WallObj[4];
WallObj[] wallObjs = new WallObj[4];
for (int i = 0; i < 4; i )
{
wallObjs[i] = transform.GetChild(i 1).GetComponent<WallObj>();
wallObjs[i].setWallState((int)roomData.entryInfo.i);
}
foreach (WallObj wall in wallObjs)
{
wall.adjacents(roomData.dunGrid, roomData.abstRoom);
}```
CodePudding user response:
You may check Access property by Index, it helps you to access roomData .entryInfo with for loop index.
But I think it's not a good idea to make code less readable for "cleaner"
CodePudding user response:
Unity's Vector4
supports the index operator exactly as you describe.
Just use (int)roomData.entryInfo[i]
.
That being said, pulling ints from float fields is a bit clunky and if you really aren't storing floats, you may consider implementing your own Vector4Int
type that is backed with integers and supports the index operator.
CodePudding user response:
As far as I'm aware you can't pass in variables to access a specific component of a vector like you would with an array. One possible solution for your problem might be to have a method in the wallObjs
class that does exactly what you're doing but a bit more hidden, but that depends on how much you need to do this. If you're only doing this once, you might just have to suck it up and deal with the ugly code, unfortunately.