Question by
tallesmaziero · Jan 06, 2020 at 01:27 AM ·
arrayspriteswapswapping
Swap Sprites of 2 arrays of gameobjects and vice versa
I want to change the sprites of all the objects of 2 arrays. Like a chess borad, i want to swap sptites of all black houses with white houses and vice versa every 0.5 seconds.
There is a bool swap to say where it starts.
All the houses of the chessboard are children of the object that is attached this script and are create dinamically at the beggining of the game.
I can fill the 2 arrays with the respectives gameobjects but when i start the bool swap nothing happens. I think the foreach loop is not working.
any help will be thanked in advance
this is the code:
public class SwapTiles : MonoBehaviour {
public GameObject[] tile1Object;
public GameObject[] tile2Object;
public bool swap = false;
public bool getTiles = true;
public float swapTime = 0.5f;
public Sprite tile1;
public Sprite tile2;
// Update is called once per frame
void Update()
{
if (getTiles)
{
tile1Object = GameObject.FindGameObjectsWithTag("Tile1");
tile2Object = GameObject.FindGameObjectsWithTag("Tile2");
getTiles = false;
}
if (swap)
{
SwapSpriteTile();
}
}
private void SwapSpriteTile()
{
StartCoroutine(SwapTime());
foreach (GameObject tile in tile1Object)
{
tile.GetComponent<SpriteRenderer>().sprite = tile2;
}
foreach (GameObject tile in tile2Object)
{
tile.GetComponent<SpriteRenderer>().sprite = tile1;
}
StartCoroutine(SwapTime());
foreach (GameObject tile in tile1Object)
{
tile.GetComponent<SpriteRenderer>().sprite = tile1;
}
foreach (GameObject tile in tile2Object)
{
tile.GetComponent<SpriteRenderer>().sprite = tile2;
}
}
IEnumerator SwapTime()
{
yield return new WaitForSeconds(swapTime);
}
}
Comment