Game Development Reference
In-Depth Information
Figure 7-22.
The contents of the New Area array on Occluder
A more abbreviated way to iterate through an array is the
foreach
loop. Because
foreach
loops do
not require a
length
to know when to stop, they have the advantage of being able to iterate through
lists. Lists are a close relative of arrays. Unlike arrays, you cannot get their length, but their length
can
be dynamically changed during run time. Let's get the contents of the
newArea
array with the
foreach
loop.
Below the closing curly bracket for the
for
loop, add the following:
6.
print (""); // do a carriage return
foreach(GameObject theElement in newArea) {
print (theElement.name); // print the name of the current element
}
7. Save the script, and click Play.
The results are the same. The
foreach
loop goes through the array, assigning each to a temporary
variable of type GameObject, prints its name, and continues going through the array until it has
come to the end of the array. The
foreach
is perfect for doing something to each element in an array.
Let's use the
foreach
loop to change the active state on the array elements.
Delete or comment out the contents of the
Start
function.
8.
Add the following to the
OnTriggerEnter
function, inside the
if
clause:
9.
foreach(GameObject theElement in newArea) {
theElement.SetActive(state); // set the object's active parameter to state
}
The
SetActive
function or method will set the object and all of its children on or off according to
whether you use
true
or
false
as its argument.
10.
Save the script.
You will require four occluder triggers for each gate, so this will be a good candidate for a prefab.
1.
In the Prefabs folder, create a new folder and name it
Misc
.
2.
Drop the Occluder object into the new folder.