Unity C# Basics — Light Show


The focus for this mini project is on For Loops and how we can use it to loop forward and backwards through an array of objects and change the color of them.

The Code Breakdown

We will first need to to create an empty array of Light types and give it a SerializedField attribute, so we can fill the array with the point lights in the Inspector.

Now the Light array is filled with the Point Lights in the scene, we are going to loop through each one and change the color. We want to wait a certain amount of time between each light so a Coroutine is needed to give us access to Yield Return New WaitForSeconds (amount of time).

The syntax for the For Loop is…

for (int i = 0; i < Loop Amount; i++)

The i variable represent the Index and is a whole number. It is going to start at 0 (i = 0). The next part is going to check to see if the Index(i) is less than the length of the lights array which is 6 (i < _lights.Length), so that is True. Since that condition is True, then it will increment the Index (i) by 1 (making i = 1) after running the code in the Loop. This will continue to repeat unit the Index value (i) is no longer than less than the length of the lights array (6).

The code that is running in each iteration of the Loop is…

_lights[i].color = Color.green;

_lights[i] gives use the Point Light in the array that is equal to the current index value. We append that with color; given us access to the color of the light and we can set to whatever color we want. Lastly, we wait for amount of time in the WaitForSeconds before running the next iteration of the loop.

In this For Loop is working backwards through the array by first setting the Index value (i) to the length of the array (6), checking to see if (i) is greater than or equal to 0, and decrementing (i) by 1.

The Code

I hope this helps someone! Cheers!