In previous chapters, we learned how to tell Unity what to do line by line. In most of our examples, we wrote one instruction per line. I want to move on to something a bit more complex now.
In this chapter, we will cover the following topics:
Loops are an essential technique when writing any software in pretty much any programming language. By using loops, we gain the ability to repeat a block of code X number of times. There are many variants of loops in C#. We will talk about the most common loops:
The foreach
loop
The for
loop
The while
loop
The foreach
loop is very simple to use. It also has the simplest syntax. We use the foreach
keyword followed by brackets in this loop. Inside the brackets, you must specify the type of data you want to iterate through inside your loop. Pick a single element variable name. You can name it whatever you like. This name is used to access this variable inside the main loop block. After the name, we write the in
keyword, followed by our List variable name, as shown here:
I know it's quite confusing now, but don't worry too much about the theory. All you need to know as of now is that the code inside the foreach
loop is called as many times as there are elements in myCollectionVariable
. So, if myCollectionVariable
contains 10 elements, the code inside the loop block (highlighted in pink) will be executed 10 times.
To make it a bit more eye friendly, let's look at an actual code example. We will use the family members example from the previous chapter and print every element inside...
You have learned about foreach
loops. When iterating through a foreach
loop, we can use a local variable directly to access the data we need. In a for
loop, we also create a variable. However it is an integer variable for controlling the execution of the loop and accessing the data inside the collection by index.
There are three fundamental parts of the for
loop. It will look a bit scary to you at the beginning, but try not to run away.
The for
loop's syntax might look overcomplicated, but trust me, it isn't! Let's go through all of its elements one by one.
The for
loop begins with the for
keyword, followed by brackets. Inside the brackets we must have three fundamental elements separated by semicolons:
Initializer: The initializer is simply a declared variable that is assigned a value. In the preceding code, we declared a variable called i
of the int
type and assigned it a value of 0
.
Condition: The condition must be true for the code block to be executed. In this example, the...
There is one more type of loop that I want to talk about. It has pretty much the simplest form of any loop. The while
loop does not create any variable to control its execution. To create a while
loop, start with the keyword while
, followed by brackets. Within the brackets, you must write a condition. Whenever the condition is true, the code inside the loop block will be executed:
It's worth knowing that this is quite a dangerous loop and you need to know how to use it. As a while
loop does not create any control variable and is not iterating through the list there is a possible scenario where a condition is always true. This will create an infinite loop—a loop that will go on forever. An infinite loop never finishes executing the loop block, and most certainly, it will crash your program and even Unity Editor.
To avoid this nasty situation—when Unity crashes and we don't even know why—we can use a variable to control the flow of the while
loop, like we did in our for
loop....
Both while
and for
loops do the same thing. I bet you are wondering why we should even bother learning them both. A for
loop is great for iterations through arrays and lists. A while
loop is great for holding code execution until a condition isn't met.
I don't want you to worry about while
loops for now. We will go through more complex examples when you learn about coroutines in Unity. A coroutine is a special type of method in Unity that can run through an infinite loop without crashing. Let's forget it for a few chapters. We will definitely use them in the second half of the book, when you will be building your first game!
You have learned the fundamentals of the three basic loops. Let's have some fun now. You can write virtually any code inside a loop block.
Why don't we insert some if
statements inside our code block and ask Unity to make the decisions? Let's iterate through a for
loop 100 times and print on the Unity Console some useful information about the i
variable's value, as follows:
Let's analyze the code:
Line 9: This is the declaration of the for
loop. The condition for our loop is i < 100
, which means that we will run the loop 100 times with the value of i
increasing from 0 to 99.
Line 11: This contains a simple if
statement that checks whether i
is equal to 0
. As the i
value increments every time the loop runs through, line 12 will be executed only once, that is, on the first loop run.
Line 14: This contains if
statements that call the IsNumberEven
function, which returns bool
. I know this feels very complicated now, but it is deliberate...
Take a look at line 26. The %
operator is called modulo. Modulo computes a remainder. The modulo operator provides a way to execute code once in every several iterations of a loop. We are using modulo here to check whether a number variable can be perfectly divided by 2. If the number can be divided, the reminder will be equal to 0, so we will have an even number! Otherwise, the number must be odd.
Coming back to line 14, as a method is a substitute for a value and IsEvenMethod
is a return
type method, returning Boolean value inside if
statement. In simpler words, when the value of i
is passed to IsEvenNumber
, the method returns a true or false value. If the value is true, line 15 will be executed and the message will be printed on the Console window.
Let's test the code. If all goes well, you should see lots of messages printed on the Console window, as follows:
All went very well then! Go ahead and try to experiment with this code. Why not run the loop 1,000 times? Do it! Computers...
Searching for data inside an array
Very often, you will need to get a single element inside an array. It's very straightforward as long as you know the specific index your element is stored under. If you don't, you can search for it by iterating through the entire array object.
Yet again, let's go back to the familyMembers
example and try to look for the index of the "Adam"
string value:
We are not going too much into the details. The easiest way of finding the index of a certain element in the collection is by looping through the array and comparing elements. You can spot that on line 22. If the familyMembers[i] == "Adam"
condition is true, line 23 will be executed. The adamsIndex
variable will be then assigned the current i
value.
Notice the default value of adamsIndex
. I deliberately assigned it -1
so that we can check on line 29 whether there were any changes to this value inside the loop. If it's still -1
, it means that the value we are trying to find inside the array was not found at...
Loops can also be designed to stop themselves from executing any further. To do this, we use the break
keyword. Whenever Unity executes a line containing the break
keyword, it will stop the loop it is in and continue executing from the line just after the loop block.
We use break
mainly for performance reasons. In the preceding example, we are looking for the "Adam"
string. Once we've found it, there is no reason to iterate through the remaining elements of the loop. So, line 24 breaks the loop and the execution jumps to just after the loop block—line 27.
Hey! You are doing really well. In this chapter, you learned how to ask Unity to loop through sections of code and do something useful. In the next chapter, we will dive into the subject of organizing your code and object-oriented programming.