- Home /
How do I alternate the colors of my Chessboard?
Okay, so I've managed to make my script generate a set of tiles, 8x8, as in a chessboard, but the problem is that I don't know how to alternate the colors, i.e my sprites that I have set up, on my tiles. I've tried making an int that changes and where the tiles get generated I put some if-statements but that didn't work, the pieces just turned black. I don't know how to make the colors alternate and I couldn't find anything helpful on google either. So it'd be great if you could explain to me what I need to do, and please don't post something that says that I have to do something advanced.
Anyways, here's my script so far:
using UnityEngine;
using System.Collections;
public class Board : MonoBehaviour
{
public Sprite wT;
public Sprite bT;
public GameObject emptyTile;
public int[] whiteTileNums;
void Start ()
{
whiteTileNums = new int[4];
whiteTileNums[0] = 2;
whiteTileNums[1] = 4;
whiteTileNums[2] = 6;
whiteTileNums[3] = 8;
for(float x = 0; x < 8; x++)
{
for(float y = 0; y < 8; y++)
{
Vector2 newTilePos = new Vector2(x - 3.6f, -y + 3);
GameObject newTile = (GameObject)Instantiate(emptyTile, new Vector3(newTilePos.x, newTilePos.y, 0), Quaternion.identity);
newTile.GetComponent<SpriteRenderer>().sprite = wT;
}
}
}
}
Answer by NoseKills · Apr 11, 2015 at 08:12 AM
If (x+y) is an even number, use the other tile, if not use the other.
if ((x+y) % 2 == 0)
newTile.GetComponent<SpriteRenderer>().sprite = wT;
else
newTile.GetComponent<SpriteRenderer>().sprite = bT;
Answer by pulkitarora · Apr 11, 2015 at 02:56 PM
//in case if it helps
using UnityEngine; using System.Collections;
public class Board : MonoBehaviour {
public Sprite wT;
public Sprite bT;
public GameObject emptyTile;
public int counter = 0 ;
public int[] whiteTileNums;
void Start ()
{
whiteTileNums = new int[4];
whiteTileNums[0] = 2;
whiteTileNums[1] = 4;
whiteTileNums[2] = 6;
whiteTileNums[3] = 8;
for(float x = 0; x < 8; x++)
{
for(float y = 0; y < 8; y++)
{
Vector2 newTilePos = new Vector2(x - 3.6f, -y + 3);
if(counter % 2 == 0 ) { //call for white/black }else { // call for the white/black } counter++;
GameObject newTile = (GameObject)Instantiate(emptyTile, new Vector3(newTilePos.x, newTilePos.y, 0), Quaternion.identity);
newTile.GetComponent<SpriteRenderer>().sprite = wT;
}
}
}
}
Your answer
Follow this Question
Related Questions
Clicker game instantiate prefab depending on gold per click 0 Answers
Instantiate object in for loop with array 2 Answers
Instantiate for loop skips some objects 1 Answer
How can I naming each instantiated object in "for" loop ? 1 Answer
Having multiple objects fire prefabs in different times C# 0 Answers