Bubble Shooter Game in Unity: Part 7

We need to remove all balls (bubbles) which are no longer connected to the main body of the grid.

I do this with a new method in the Grid class, called right after I remove matches from the grid.

void CheckForDisconnected () {
//set all balls as disconnected
foreach (var r in gridBalls) {
foreach (var b in r) {
b.connected = false;
}
}
//connect visible balls in first row
foreach (var b in gridBalls[0]) {
if (b.gameObject.activeSelf)
b.connected = true;
}

//now set connect property on the rest of the balls
var i = 1;
while (i < ROWS) { foreach (var b in gridBalls[i]) { if (b.gameObject.activeSelf) { var neighbors = BallActiveNeighbors (b); var connected = false; foreach (var n in neighbors) { if (n.connected) { connected = true; break; } } if (connected) { b.connected = true; foreach (var n in neighbors) { if (n.gameObject.activeSelf) { n.connected = true; } } } } } i++; } }

The Ball now has a property called connected. I set it to false initially, and then I make every visible ball in the first row connected. The first row is "anchored" to the screen, so any visible ball in that row, is "connected."

Then I check ever subsequent row and check if a ball is touching a connected cell. If it is, that ball and all its neighbors are set to be connected.

Next I remove the disconnected balls:

public void CheckMatchesForBall (Ball ball) {

matchList.Clear ();

for (int row = 0; row < ROWS; row++) { for (int column = 0; column < COLUMNS; column++) { gridBalls [row] [column].visited = false; } } //search for matches around ball var initialResult = GetMatches( ball ); matchList.AddRange (initialResult); while (true) { var allVisited = true; for (var i = matchList.Count - 1; i >= 0 ; i--) {
var b = matchList [i];
if (!b.visited) {
AddMatches (GetMatches (b));
allVisited = false;
}
}

if (allVisited) {
if (matchList.Count > 2) {

foreach (var b in matchList) {
b.gameObject.SetActive (false);
}

CheckForDisconnected ();

//remove disconnected balls
var i = 0;
while (i < ROWS) { foreach (var b in gridBalls[i]) { if (!b.connected && b.gameObject.activeSelf) { b.gameObject.SetActive (false); } } i++; } } return; } } }

So when I run the logic that removes matches, I re-check for disconnected cells and then just remove them.

You might want to add a nice delay here between matches removed and disconnected balls being removed, or make the disconnected balls fall off the screen. However you want to handle it, it would start here.

Here is the project so far.

Next, I'll convert the grid to a Hex grid.