Alternate the direction that a grid updates, and/or change the conditions to a For Loop mid-loop.
I'm currently making a falling sand game, and right now the movement of the sand particles favors the direction the grid updates. So with the code
for (int x = 0; x < gridXY.x; x++)
sand particles are more inclined to move right, and with
for (int x = gridXY.x; x>0, x--)
sand particles are more inclined to move left.
My thought is that the best solution would be to just alternate between these every frame, but I don't know how to do that without making a full copy of the code with that one change and setting up the code to alternate between them. Since this will be a persistent problem with much more complicated particles this doesn't seem practical. Is there a way to 'hotswap' the conditions for the For Loop every frame, or an entirely different way I could be doing this that would be functionally the same?
Full code for the sand particle movement below.
private void SandBehavior()
{
for (int x = 0; x < gridXY.x; x++)
{
for (int y = 0; y < gridXY.y; y++)
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y, 0)) == sand) //if tile is sand
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x, y - 1, 0)) == null)
{ //if tile below is empty, move there
tilemapNext.SetTile(new Vector3Int(x, y - 1, 0), sand);
}
else if (tilemapCurrent.GetTile(new Vector3Int(x - 1, y - 1, 0)) != null && tilemapCurrent.GetTile(new Vector3Int(x + 1, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x + 1, y - 1, 0)) == null)
{ //if only 1 down 1 right empty, move there
tilemapNext.SetTile(new Vector3Int(x + 1, y - 1, 0), sand);
}
else if (tilemapCurrent.GetTile(new Vector3Int(x - 1, y - 1, 0)) == null && tilemapCurrent.GetTile(new Vector3Int(x + 1, y - 1, 0)) != null && tilemapNext.GetTile(new Vector3Int(x - 1, y - 1, 0)) == null)
{ //if only 1 down 1 left empty, move there
tilemapNext.SetTile(new Vector3Int(x - 1, y - 1, 0), sand);
}
else if (tilemapCurrent.GetTile(new Vector3Int(x - 1, y - 1, 0)) == null && tilemapCurrent.GetTile(new Vector3Int(x + 1, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x - 1, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x + 1, y - 1, 0)) == null)
{ //if both empty, move to one at random
{
int randomNumber = Random.Range(0, 2);
if (randomNumber == 0)
{
tilemapNext.SetTile(new Vector3Int(x - 1, y - 1, 0), sand);
}
if (randomNumber == 1)
{
tilemapNext.SetTile(new Vector3Int(x + 1, y - 1, 0), sand);
}
}
}
else
{ //if no tiles below empty, maintain position
tilemapNext.SetTile(new Vector3Int(x, y, 0), sand);
}
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613051423im_/https://answers.unity.com/themes/thub/images/avi.jpg)