Why does this foreach loop break without a break statement?

Edit: It was the cause of a completely different issue with double die resulting in double points which meant that the check to see if the numbers were the same didn’t work.

I’m trying to make the knucklebones game from Cult Of The Lamb but I have a problem. What I’m trying to do is when you place down a die, it checks to see if any of the squares in the column above it have the same number as the die, if they do then get rid of them. This works when it’s only one same numbered die in the above column, but if there’s multiple die, it will only delete one of them and keep the rest. Why does this happen?

foreach ( GameObject squareAboveObj in square.squaresAbove )
{
    Square sqrAbove = squareAboveObj.GetComponent<Square>();
                   
    if ( !sqrAbove.diceOnSquare )
    {
        Debug.Log("no dice on square so we ignore it");
        continue;
    }
    // check if the die above is on the same number as the die we just placed
    if ( sqrAbove.points == square.points )
    {
        var diceSprite = sqrAbove.diceOnSquare.GetComponent<SpriteRenderer>();

        diceSprite.DOColor(Color.red, 1);
        Destroy(diceSprite.gameObject, 1);
        Debug.Log("deleting square"); // this only runs once
    }
}

Three possibilities:

  • There is only one objects in the square.squaresAbove collection
  • Only one object in that collection satisfies the sqrAbove.points == square.points check
  • There is some exception being thrown in the code, causing the rest of the code to no longer execute.

Only you can answer the question of which is happening here. You need to add more logs and look out for exception logs to find out which one it is. Here’s some things I think you should be logging to diagnose this issue properly:

  • square.squaresAbove.Count or square.squaresAbove.Length depending if it’s a List or an array

  • square.points

  • sqrAbove.points