Unity C# Basics — One Light On At A Time

Intro

This mini project will turn on one random light at a time and display the color of the light that is on. This project focused on using Arrays and Foreach Loops.

The Code Breakdown

In the main script SimonSays (I was trying to recreate Simon Says, but realized Lists are needed), we create another class Cubes that will populate the array we want to access.

In this new class, Cubes, we are going to give each light a number (cubeID), we need access to each of the lights (light), the color name of the light (colorName), and the text that will display the light that is on (colorText). We want to be able to access these variables in the Inspector so we need to give the header of [System.Serializable].

In the SimonSays portion of the script, we are going to make an array [] of the class Cubes.

Looking at the Inspector you can see how each Element of the array TheCubes has each of those variables we declared in the Cubes class. Now we can just assign each of lights, give them their color name, assign the text, and give them their cube ID. Now our array is populate we can go over how to access each of the elements in the array using a Foreach Loop.

In the On Start, we can loop through each array in using a foreach Loop. The syntax requires a var (variable), which Unity will be able to distinguishes the variable type in the array, the name you want to give this variable that will represents each of the array items, the key word — in — , and the array you want to loop through (theCubes).

Now, we can loop through each of the array elements and access each item individually. At the beginning we want to turn off all of the lights and make the text be nothing.

In the Update, when we press the space bar, we want to pick a random number. We are going to create local var (randomID) and have it pick a random number from 0 to the length of the cubes array (3).

We use the foreach loop to loop through each of the items in our array and when we do that we can apply some logic. If the random number that was picked is each to the cubeID in the array we will turn on the light of that cube, we will set the text to the color name and set the color of text to the light’s color.

If the random number doesn’t match the cubeID, we simply just want to turn off the light and have the text be nothing. This helps turn off the previous selection and have the new random light and text displayed when the space bar is pressed.

There is my idea of how a foreach loop can be used with an array. Until next time, cheers!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store