- Home /
How to move cells in a 2d array
Hi people,
I am trying to move cells in the opposite direction in a 2d array for a match 3 game. Below is the script i am using
private void DoEmptyDown(ref GameObject[,] cells)
{ //replace the empty tiles with the ones above
for (int x= 0; x <= cells.GetUpperBound(0); x++)
{
for (int y = 0; y <= cells.GetUpperBound(1); y++)
{
var thisCell = cells[x, y];
if (thisCell.name == "Empty(Clone)")
{
for (int y2 = y; y2 <= cells.GetUpperBound(1); y2++)
{
if (cells[x, y2].name != "Empty(Clone)")
{
cells[x, y] = cells[x, y2];
cells[x, y2] = thisCell;
print ("done");
break;
}
}
}
}
}
}
As it is the script works fine, and shifts the gameobjects and fills the empty cells downwards. How can i shift the cells upwards instead of downwards. Below is what I have been trying to no luck to far. Only the immediate row moves up.
private void DoEmptyDown(ref GameObject[,] cells)
{ //replace the empty tiles with the ones above
for (int x= 0; x <= cells.GetUpperBound(0); x++)
{
for (int y = 0; y <= cells.GetUpperBound(1); y++)
{
var thisCell = cells[x, y];
if (thisCell.name == "Empty(Clone)")
{
for (int y2 = y; y2 >= cells.GetLowerBound(1); y2--)
{
if (cells[x, y2].name != "Empty(Clone)")
{
cells[x, y] = cells[x, y2];
cells[x, y2] = thisCell;
print ("done");
break;
}
}
}
}
}
}
Kindly assist. Thanks
There's nothing Unity-special about this. $$anonymous$$aybe someone wants to rewrite an old answer here. But I'd guess "shift 2D array" would pop up useful stuff.
Also, drawing a picture, with 0-n labels, often helps.
I'm not 100% clear what you're after, but have you tried making the for loop on line 5 count y down from UpperBound ins$$anonymous$$d of counting up from zero?
To echo what the guys here are saying, the middle for-loop at line 5 should probably count backwards in the second example since you want to start checking empty spaces from the direction the pieces would be falling to.
And since there's nothing magical happening here, drawing the grid on paper and following through the code loops while looking at the image should give you an understanding what's happening.
Your answer
Follow this Question
Related Questions
Make your player not move during a animation? 0 Answers
move character controller forward using gui button. 1 Answer
objects to move when picked up 0 Answers
c# not going to destination on 0 hp 1 Answer
Monster doesn't move 0 Answers