Layman explanation please

As I progress through the course, I often take a lilttle time, and print out my code, then attempt to talk it out while marking it with a pencil. Helps me out. There is one line of code, that for some reason I can’t wrap my head around. Please break it down into as non-technical terms as possible, to help me fully understand it.


Cheers!
JP

1 Like

JP,

There’s a piece of information we need to be able to help out. Namely, what is “transform” in this context? Where is it set, and to what? It stands to reason that it’s a list or array or some other collection (that’s the only way it can be used that way in a foreach loop), but knowing exactly what it is will get us further than a general explanation.

Just in case the confusion is in the generics, though, the line you posted is a standard “for each” loop structure. These work in a very similar way to regular “for” loops, but foreach loops do not use an integer, but rather access the objects themselves, In fact, under the hood it IS a for loop. Let’s look at an example.

//Say we have some array:
string[] stringArray = new string[4] {"str1", "str2", "str3", "str4"};
//And we want to print out each element in it. We do this with a foreach loop!
foreach (string str in stringArray) {
    Debug.Log(str);
}

//THIS WILL OUTPUT:
// str1
// str2
// str3
// str4

Now, under the hood, the compiler is still using the index to know when we’ve reached the last object (“str4”) and exit the loop. But inside the loop, what we’re doing is iterating over the elements of the loop, instead of just an index. This makes it easier to access objects a lot within a loop, and is more readable in many cases.

Now, this is just a guess, since I don’t know what the “transform” variable is in your code, but it looks like your line works as follows:

It looks like your “transform” variable is probably a list of all Gameobjects childed to a Gameobject with some Transform (in which case I would rename that variable, maybe to childTransforms). This foreach loop knows that “transform” is that list, and that it contains objects of type Transform. childPositionGameObject is the direct reference to an object in that list, exactly like “str” was in my example.

So, as best I can put it into layman’s terms:

“Go through the list of objects called transform, which contains things of type Transform. Execute the following code once for each thing in that list, and we’ll call that thing childPositionGameObject for ease of reference.”

5 Likes

Thank you! That was perfect. It was one of those things where understanding was almost there, but on the tip of the tongue! I really appreciate the time!

JP

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.