Using Loops (For, While) to Repeat Code Execution

Loops are essential programming constructs that allow you to repeat code execution based on specific conditions. In Unity, you can use loops, such as the for loop and the while loop, to iterate over collections, perform repeated actions, or control the flow of your code. Here's an overview of using loops in Unity:

'For'

The 'for' loop is commonly used when you know the number of iterations in advance. It consists of three parts: initialization, condition, and iteration. The loop variable is initialized, and as long as the condition is true, the loop body is executed. After each iteration, the loop variable is updated. Here's an example of a 'for' loop:

for (int i = 0; i < 10; i++)
{
    // Code to be executed for each iteration
    Debug.Log("Iteration: " + i);
}

In this example, the loop will execute 10 times, with the loop variable 'i' ranging from 0 to 9. Adjust the loop variable initialization, condition, and iteration to suit your needs.

'While'

The 'while' loop is used when you want to repeat code execution as long as a specific condition is true. It continues executing the loop body until the condition evaluates to false. Here's an example of a 'while' loop:

int count = 0;
while (count < 5)
{
    // Code to be executed for each iteration
    Debug.Log("Iteration: " + count);
    count++;
}

In this example, the loop will execute until the 'count' variable reaches 5. Adjust the condition to control how many times the loop will iterate.

Exiting a Loop

Sometimes, you might need to exit a loop prematurely based on certain conditions. You can use the 'break' statement to immediately exit the loop and continue execution outside the loop body. Here's an example:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        // Exit the loop when i is 5
        break;
    }
    Debug.Log("Iteration: " + i);
}

In this example, the loop will exit when the 'i' reaches 5.

Skipping an Iteration

To skip the current iteration and proceed to the next one, you can use the 'continue' statement. It immediately jumps to the next iteration without executing the remaining code in the loop body. Here's an example:

for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        // Skip even numbers
        continue;
    }
    Debug.Log("Iteration: " + i);
}

In this example, the loop will skip even numbers and only execute code for odd numbers.

Conclusion

Loops provide powerful tools for controlling code execution flow and repeating actions in Unity. Choose the appropriate loop construct based on your specific requirements, whether you know the number of iterations in advance ('for') or need to repeat code as long as a condition is true ('while').

Links
Unity 6