What does For do and how do I use it.

I’m still rather new to unity so I’m not sure what For () does and how I use it.

a for-loop is not Unity specific.

for(var i = 0; i < 10; i++)
{

}

if you didn’t meant a for loop but rather a For method. Then I don’t know what you’re talking about and you would need to provide more context. if that’s the case then share a code snippet with code tags.

Also the Unity learn has some tutorials for scripting beginners.

for loops exist in pretty much all existing programming languages. This includes the language that Unity understands, which is called C#.

In its basic form, a for loop basically repeats a block of code a certain amount of times. The one MaskedMouse posted would repeat whatever’s within the curly brackets 10 times.

The 3 parameters of the for loop can be anything; for example

 int iter = 0;
 for (GameObject C = null; C != null; iter++)
{
   if (iter == 1)
      C = new GameObject();
}

We are effectively initiating a numerator. A counter of some extent that occurs within the frame. This is the iteration part, you may set the value of the iterator on the first part and define a condition in the second part.

for (int iter = 0; iter < 1; iter++)

Here is another exotic example

for (int iter = 0; iter != -1;)
{
         if (BOOL)
         iter = iter - 1;
         else
         iter = iter + 1;
}
1 Like

While we’re talking about loops, the foreach statement is very useful :slight_smile:

foreach (var thing in someList) {
  thing.reticulateSplines();
}

It’s a lot more straightforward, as long as you don’t need to store things into the list you’re iterating over.

You can’t just drop foreach in a conversation and confuse a beginner without explaining all the caveats and use cases.

Let’s break this down.
In imperative programming we regularly come across situations where we would like to repeat some kernel action multiple times, either a) a set amount of times (known in design time), or b) a variable amount of times (known in run time).

You can always implement this manually, but if the amount of repetitions surpasses 3-4 and/or the kernel is large enough, this becomes a burden on the eyes and clarity of the code. Repeating code is also inviting to introducing bugs by accidentally omitting to update the redundant code. The solution? Don’t repeat yourself unnecessarily.

In some other situations, loops help solve some critical algorithms, allow nested loops, and otherwise are used to scan all kinds of linearly allocated data (by index).

For this reason, all industrially-recognized programming imperative languages include the intrinsic syntax to specify a loop, and ever since C was invented these have solidified in three flavors: for, do, and while.

For is the general purpose one, that is intended for use with counters. What is a counter? Well, you want to count how many cycles are there in order to have control over the loop. This cycle is also called iteration. And having no control over the loop or its iterations will lead you to “infinite loop” which is undesirable, because short of ending the system process (in modern operating systems) there is no way to stop it.

Here is more information on what for does for you (and the patterns that frequently come up with its usage). And some more .

You’re supposed to also learn more about the control mechanisms, as well as the contextual keywords break and continue which are very important to master the loop structure. You can find a load of C# tutorials and examples on the web.

Unlike for, while and do are not explicitly counter-based and have a lighter syntax. These are supposed to be used with boolean expressions, like ifs.

For example, where this would trigger only once

if(value > 15) {
  value -= 5;
}

This would trigger as many times as needed until the condition becomes satisfied

while(value > 15) {
  value -= 5;
}

Do is just a variant where the condition evaluates after each iteration. So this wouldn’t behave exactly the same as before. It is also guaranteed that the code will be executed at least once.

do {
  value -= 5;
} while(value > 15);

And finally, C# also has foreach, which, contrary to its usage similarity to for, doesn’t actually work the same way. Foreach keyword is tightly coupled to a concept of enumerables in C#. It is just a feature of convenience that lets you iterate through an enumerable collection by calling an IEnumerable interface method called MoveNext and it’s not just a simple loop, there are things going on in the background. This has several important effects: it may allocate memory, it calls stuff, it relies on the internal state which you mustn’t change (for example, you cannot modify the collection you’re iterating through). Because of all of this, and depending on the quality of your collection, it might be slow(ish), but it is hyper-convenient and compact for cases where you don’t need counters, and you can assign the objects of interest directly.

Here’s a comparison between iterating through a list which contains game objects with for and foreach.

List<GameObject> list = getListOfObjects();
for(int i = 0; i < list.Count; i++) {
  var obj = list[i];
  // use obj
}
foreach(var obj in getListOfObjects()) {
  // use obj
}

When working with non-indexed collections, this is usually the preferred way of iterating over the elements.
In this example, I use a HashSet to come up with a list of unique game objects to be used at a later point in time.

var hset = new HashSet<GameObject>();
foreach(var obj in getListOfObjects()) {
  if(!hset.Contains(obj)) hset.Add(obj);
}

// later
// HashSet has no indice, so this is the only way to reach for its elements
// also the order is unspecified
foreach(var obj in hset) {
  Debug.Log(obj.name);
  // observe that I'm not allowed to change hset (with Add or Remove) while inside of this loop
  // whereas that would be legal with for, while, or do
}

The reason why you can use foreach instead of for nearly wherever with these standard collections is because all of them implement IEnumerable interface. However you are still strongly encouraged to think in terms of simple for loops for speed and precision whenever possible. Also if you really want to maintain counters (and we mostly do) for certain algorithms, UI behavior and whatnot, you’d use for, otherwise you’d have to add a new variable and count iterations yourself (which isn’t unheard of, this may happen from time to time, although rarely).

As a dumb example, because this isn’t practical and there are better ways to organize this, this is how you would count up all game objects whose names begin with some specific character.

int CountObjectsStartingWith(char c, IEnumerable<GameObject> objects) {
  var count = 0;
  foreach(var obj in objects) {
    if(obj.name.StartsWith(c)) count++;
  }
  return count;
}

Nice and detailed explanation @orionsyndrome !

I’m afraid it will pass quite some time before OP can make heads or tails of it though, he came asking what a for loop is and got IEnumerable’d. :smile:

Do us a 6 pager it’s dead on weekends anyway. OP abandoned ship maybe he already knew what a for loop was !? Maybe was just a bluff.

@arkano22
It’s hard not to get IEnumerable’d in C#. The sooner the OP confronts them, the better.