Trouble Building Chessboard

I have this code:

    void BuildBoard() {

        for (int x = 0; x < 5; x++) {

            for (int y = 0; y < 5; y++) {

                if (y % 2 == 0) {

                    Instantiate (BlackSquare, new Vector3( y + 2, x + 2, 0), Quaternion.identity);
                } else {

                    Instantiate (WhiteSquare, new Vector3( y + 2, x + 2, 0), Quaternion.identity);
                }
            }
        }
    }
}

I’m trying to instantiate squares that are 600 x 600 px, but I keep getting this:

What’s wrong with my code?

Thanks in advanced

That’s pretty much what you told it to do. For a chess board pattern try:

void BuildBoard() {
    for (int x = 0; x < 8; x++) {
        for (int y = 0; y < 8; y++) {
            if ((y + x) % 2 == 0) {
                Instantiate (BlackSquare, new Vector3( y + 2, x + 2, 0), Quaternion.identity);
            } else {
                Instantiate (WhiteSquare, new Vector3( y + 2, x + 2, 0), Quaternion.identity);
            }
        }
    }
}

For a more dry approach consider

void BuildBoard() {
    for (int x = 0; x < 8; x++) {
        for (int y = 0; y < 8; y++) {
            GameObject nextSquare;
            if ((y + x) % 2 == 0) {
                nextSquare = blackSquare;
            } else {
                nextSquare = whiteSquare;
            }
            Instantiate (nextSquare, new Vector3( y + 2, x + 2, 0), Quaternion.identity);
        }
    }
}
1 Like

My new code is

void BuildBoard() {

        for (int x = 0; x < 7; x++) {

            for (int y = 0; y < 7; y++) {

                if (x % 2 == 0) {
                    if (y % 2 == 0) {

                        Instantiate (BlackSquare, new Vector3( y * 2, x * 2, 0), Quaternion.identity);
                    } else {

                        Instantiate (WhiteSquare, new Vector3( y * 2, x * 2, 0), Quaternion.identity);
                    }
                } else {
                    if (y % 2 == 0) {
                      
                        Instantiate (WhiteSquare, new Vector3( y * 2, x * 2, 0), Quaternion.identity);
                    } else {
                      
                        Instantiate (BlackSquare, new Vector3( y * 2, x * 2, 0), Quaternion.identity);
                    }
                }
            }
        }
    }

But yours is probably cleaner. My other problem is that the squares are overlapping, and I would like them not to.

Fixing the overlapping is relatively straight forward. Just multiply the x and y coordinates by the size of the game objects in your instantiate function.

1 Like

wow i wish someone had linked me to this I had the same problem 3 months ago ,it was getting me depressed and this fixed it thank you every one that commented on this you are all awesome

1 Like