Suggestion for those struggling with foreach command

Hello all. Just wanted to throw out a comment that may help anyone struggling to understand the concept of foreach loops, specifically the “(GameObject laser in lasers)” part of it.

Like Rick says in the lecture, you can use almost any variable name you want to in place of “laser” in his code. Because this is allowed a trick that I found useful when starting out is instead of using the code:

foreach (GameObject laser in lasers)

I used the code:

foreach (GameObject currentLaser in lasers)

This has two benefits:

  1. ‘currentLaser’ and ‘lasers’ are much harder to get confused vs ‘laser’ and ‘lasers’
  2. The naming ‘currentLaser’ works as a helpful reminder that as you’re going through the entire array of ‘lasers’ you’re only referencing the current one of those objects

Maybe that won’t be of help to anyone, but I know it helped get foreach loops to “click” for me when I first started using them long ago.

Privacy & Terms