Simple scripting Question! Foreach

When it comes to the foreach we used:

foreach (Block waypoint in path)

How does the scripting know what ‘waypoint’ is? We never assigned anything that name. Does it just assume that anything within the list path is the second word inside the parentheses?

Thanks guys!

Hey Nibernator,

In that example, the script doesn’t actually know what “waypoint” is before that moment. You’re actually declaring something new in the parenthesis in a foreach statement. Basically:

foreach(TypeOfThing nameYou’llUseLater in PreviouslyDeclaredArray,List,Etc)

Your example is a little extra confusing as I think you asked that question in a video before Ben renamed “Block” to “Waypoint”. So I’ll assume you’re past that and just calling everything Waypoint.

path is a list of Waypoints, right? So with that for each statement, you’re asking the code to do something with each Waypoint in the list “path.” You’re declaring the word “waypoint” with lowercase, so you have something to refer to later in your code. As it goes through the foreach loop, the temporary variable “waypoint” is the first Waypoint, then the second Waypoint, etc etc. You’re just clearing it so you can access is, such as:

foreach (Waypoint waypoint in path)
{
Destroy(waypoint);
}

Hope that helps!

1 Like

Privacy & Terms