Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question A small issue with iterating through a List<GameObject> and removing objects

Discussion in 'Scripting' started by kakashidiot, Apr 21, 2023.

  1. kakashidiot

    kakashidiot

    Joined:
    Mar 10, 2019
    Posts:
    2
    Hi! I've been reading up on loops, iterating, and removing items from lists, but I'm still rather muddled in terms of my own project.

    Project Info: [see pictures below] A 2D grid that is instantiated through code. The edge tiles are located and sent to a List. From the list, a random Tile is selected and an Entrance Tile is placed. At the same time, information on every tile's neighbors is sent to each Tile. If the Tile recognizes itself as an Entrance Tile, it returns the neighbor tile information back to the Board script. Then, it removes all of its neighboring tiles from the edge tile List. The idea is that after removing these neighboring tiles, the Exit Tile triggers a second randomized selection from the new edgeList and then places itself on the board. Then the board populates with other random Tiles.

    The problem: When the edge tile looks for a randomized Tile, the edgeTiles List it's using is not updated.

    The edge tile total is 24. Minus the entrance tile, 23. Minus its neighbors, the total edgeTile List should be somewhere between 19-22. For some reason, the edge tile debug log I run is returning 23.

    However, when I run the script and look at the inspector, it is clear that the Entrance Tile is sending and receiving information on its neighbors and is in fact removing them from the edgeTile List. (See pictures below).

    I figure I must be calling the SetExit at the wrong time or something. Here's my code.

    Code (CSharp):
    1.  #region setting neighbors
    2.     public void SetNeighbors() [...]
    3.  
    4.     public void CallingNeighbors(List<GameObject> neighbors)
    5.     {
    6.         foreach (var x in neighbors)
    7.         {
    8.             neighborTiles.Add(x);
    9.  
    10.             if (edgeTiles.Contains(x))
    11.             {
    12.                 edgeTiles.Remove(x); [B][is this the problem?][/B]
    13.             }
    14.         }
    15.     }
    16.     #endregion
    17.  
    18.     #region set entrance/exit
    19.     public GameObject ChooseRandomNumber(List<GameObject> tileRandomize)
    20.     {
    21.         int randomNum = Random.Range(0, tileRandomize.Count);
    22.         GameObject randomTile = tileRandomize[randomNum];
    23.         return randomTile;
    24.     }
    25.  
    26.     public void SetEntrance()
    27.     {
    28.         GameObject entranceTile = ChooseRandomNumber(edgeTiles);
    29.         entranceTile.GetComponent<SpriteRenderer>().color = entranceColor;
    30.         entranceTile.GetComponent<SpriteRenderer>().sprite = entranceSprite;
    31.         entranceTile.name = new string("Entrance");
    32.  
    33.         edgeTiles.Remove(entranceTile);
    34.         //entranceTile.GetComponent<scriptTile>().isTileFilled = true;
    35.         entranceTile.GetComponent<scriptTile>().SetFilledStatus(true);
    36.  
    37.         SetExit();
    38.     }
    39.  
    40.     public void SetExit()
    41.     {
    42.         Debug.Log("edgetile Amt: " + edgeTiles.Count); [B][this is returning as 23 every time!][/B]
    43.  
    44.         GameObject exitTile = ChooseRandomNumber(edgeTiles);
    45.         exitTile.GetComponent<SpriteRenderer>().color = exitColor;
    46.         exitTile.GetComponent<SpriteRenderer>().sprite = exitSprite;
    47.         exitTile.name = new string("Exit");
    48.  
    49.         edgeTiles.Remove(exitTile);
    50.         //exitTile.GetComponent<scriptTile>().isTileFilled = true;
    51.         exitTile.GetComponent<scriptTile>().SetFilledStatus(true);
    52.  
    53.         isEntranceExitSet = true;
    54.     }
    55.     #endregion
    Am I calling SetExit at the wrong time or in the wrong place? Or is the edgeTile.Remove not changing across the board?

    Things I've tried:
    • moving SetExit around (so far all the spots I've chosen haven't fixed it or just wouldn't call SetExit properly)
    • attempting to populate a second list from the "new" edgeTile list and calling on that (threw an array exception for some reason?)
    • making a new "ChooseRandomNumber" method (didn't change anything)
    • limiting the trigger of SetExit to specific time with a bool (resulted in SetExit just not happening)
    Any advice is welcome! Thank you!
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,522
    There's a lot going on up there so I recommend simplifying to the tiniest possible set of data that exhibits the bug.

    And then it is time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.