public IEnumerator PopChainLoop(GridBall newGridBall) { // set this before we lose a reference to it when the new grid ball pops BallGrid currentBallGrid = newGridBall.ballGrid; currentBallGrid.SetState(BallGrid.State.Popping); List <GridBall> ballCluster = new List <GridBall>() { newGridBall }; List <GridBall> searched = new List <GridBall>(ballCluster); Queue <GridBall> searchQueue = new Queue <GridBall>(ballCluster); List <GridBall> adjacentBallsThatSurvived = new List <GridBall>(); while (searchQueue.Count > 0) { GridBall curBall = searchQueue.Dequeue(); if (curBall.ballColor == newGridBall.ballColor) { if (!ballCluster.Contains(curBall)) { ballCluster.Add(curBall); } foreach (GridBall gb in curBall.neighbors) { if (!searched.Contains(gb)) { searched.Add(gb); searchQueue.Enqueue(gb); } } } else { if (!adjacentBallsThatSurvived.Contains(curBall)) { adjacentBallsThatSurvived.Add(curBall); } } } if (ballCluster.Count >= 3) { foreach (GridBall gb in ballCluster) { gb.RemoveFromWall(); yield return(new WaitForSeconds(POP_DELAY)); } } int loopSafety = 0; List <GridBall> searched2 = new List <GridBall>(); while (adjacentBallsThatSurvived.Count > 0) { GridBall survivorBall = adjacentBallsThatSurvived[0]; searched2.Add(survivorBall); adjacentBallsThatSurvived.RemoveAt(0); survivorBall.CheckIfConnectedToWall(); if (!survivorBall.isConnectedToWall) { foreach (GridBall gb in survivorBall.neighbors) { if (!searched2.Contains(gb) && !adjacentBallsThatSurvived.Contains(gb)) { adjacentBallsThatSurvived.Add(gb); } } survivorBall.RemoveFromWall(); yield return(new WaitForSeconds(POP_DELAY)); } loopSafety++; if (loopSafety > 10000) { Debug.LogError("loop safety!"); break; } } currentBallGrid.SetState(BallGrid.State.Default); }