1
\$\begingroup\$

I need to instantiate an array of 2 elements that is floors of black and white color in an alternating pattern so it looks like a chess board. It is for my game that has 2D Dungeon Generation.

This is my current code:

public enum TileType
{
    Wall, Floor,
}

public GameObject[] floorTiles;
public GameObject[] wallTiles;
public GameObject[] outerWallTiles;

private TileType[][] tiles;
private Room[] rooms;
private Corridor[] corridors;
private GameObject boardHolder;

void InstantiateTiles()
{
    for (int i = 0; i < tiles.Length; i++)
    {
        for (int j = 0; j < tiles[i].Length; j++)
        {
            InstantiateFromArray(floorTiles, i, j);

            if (tiles[i][j] == TileType.Wall)
            {
                InstantiateFromArray(wallTiles, i, j);
            }
        }
    }
}

void InstantiateFromArray(GameObject[] prefabs, float xCoord, float yCoord)
{
    int randomIndex = Random.Range(0, prefabs.Length);
    Vector3 position = new Vector3(xCoord, yCoord, 0f);
    GameObject tileInstance = Instantiate(prefabs[randomIndex], position, Quaternion.identity) as GameObject;
    tileInstance.transform.parent = boardHolder.transform;
}

}

So this is how it looks right now (just random positions of floor prefabs):

Screenshot of dungeon with random-looking squares Screenshot of more random-looking squares

And this is what I am trying to achieve (alternating):

enter image description here

\$\endgroup\$
0

1 Answer 1

16
\$\begingroup\$

In the decision on what tile prefab to choose, you can think of it this way:
If (xCoord + yCoord) % 2 == 0, then select prefab1
If (xCoord + yCoord) % 2 != 0, then select prefab2

This ensures the tiles form a "chess-like" board.
Note that you will probably want to pass xCoord and yCoord as integers instead of floats.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You should check with odds using (xCoord + yCoord) % 2 != 0, since negative values can also be negative (but would yield -1, not 1). \$\endgroup\$
    – Alexander
    Commented May 12, 2020 at 16:30
  • \$\begingroup\$ @Alexander-ReinstateMonica This is correct, though in this instance he is only passing positive values. I edited my answer. \$\endgroup\$ Commented May 12, 2020 at 16:45
  • 2
    \$\begingroup\$ I would would avoid it just as a general habit. Sometimes it matters, sometimes it doesn't, but it's frustrating enough of a bug when it happens (particularly for new programmers, who might not have experienced the difference) that I recommend just always using != 1. It's no harder to write != 0 than it is to write == 1, so I see this as an absolute win \$\endgroup\$
    – Alexander
    Commented May 12, 2020 at 17:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .