Tier 1 Series 2

2C: Iteration Loops

Pilot Record
Student Profile
"In flight, a pilot performs a "Scan"—checking instruments one-by-one in a specific order. If the pilot stops mid-scan to remove a faulty fuse, they might lose their place and miss a critical reading.

In C#, Loops are your scans. If you attempt to modify (remove or add) items in a collection while you are in the middle of scanning it with a foreach loop, the entire "instrument panel" (the compiler) will crash."

The Concept: Scanning Logic

Choosing the wrong loop type is a primary cause of "Logic Stalls" in Unity.

foreach: A read-only scan. Fast and clean, but you cannot change the list while inside it.
for (standard): An indexed scan. Allows modification, but removing items causes index skipping.
for (reverse): The "Safety Scan." Iterating from Count-1 down to 0 allows for safe removals.
Red Flag Detected

The Audit: Spot the "Collection Crash" Error

You ask the AI: "Write a loop to check a list of active drones and remove any that have run out of battery."

// AI-Generated Code (Will Crash)
foreach (var drone in activeDrones) {
    if (drone.battery <= 0) {
        activeDrones.Remove(drone); // ERROR: Collection modified!
    }
}

You cannot change the "rack" while the AI is standing on it. Calling Remove() inside a foreach throws an InvalidOperationException, instantly killing the flight script.

Elite Telemetry

Research shows "Elite" teams achieve 15% faster lead times by keeping AI on a "very tight leash."

  • Small Batches Solving one problem at a time prevents logic drift.
  • Modular Design Localizing the "blast radius" of AI changes.
  • Tight Loops Rapid iteration with constant code review.

The Pilot's Correction

Corrective Protocol
// Corrected Code (Stable & Safe)
for (int i = activeDrones.Count - 1; i >= 0; i--) {
    if (activeDrones[i].battery <= 0) {
        activeDrones.RemoveAt(i); // Safe removal
    }
}
Your Pilot Command
> Direct the AI to use a LayerMask to optimize the Raycast search.
Next Mission
Method Signatures