Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Why does this foreach loop break without a break statement?

Discussion in 'Scripting' started by jlorenzi, Sep 12, 2023.

  1. jlorenzi

    jlorenzi

    Joined:
    May 2, 2021
    Posts:
    270
    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?
    Code (CSharp):
    1.  
    2. foreach ( GameObject squareAboveObj in square.squaresAbove )
    3. {
    4.     Square sqrAbove = squareAboveObj.GetComponent<Square>();
    5.                    
    6.     if ( !sqrAbove.diceOnSquare )
    7.     {
    8.         Debug.Log("no dice on square so we ignore it");
    9.         continue;
    10.     }
    11.     // check if the die above is on the same number as the die we just placed
    12.     if ( sqrAbove.points == square.points )
    13.     {
    14.         var diceSprite = sqrAbove.diceOnSquare.GetComponent<SpriteRenderer>();
    15.  
    16.         diceSprite.DOColor(Color.red, 1);
    17.         Destroy(diceSprite.gameObject, 1);
    18.         Debug.Log("deleting square"); // this only runs once
    19.     }
    20. }
     
    Last edited: Sep 12, 2023
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    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
     
    Bunny83 likes this.