Game Development Reference
In-Depth Information
Line 15 : Here, the first element in the array is set to the main camera object
in the scene. Two important points should be noted here. First, elements in
the array can be accessed using the array subscript operator [] . Thus, the
first element of MyObjects can be accessed with MyObjects[0] . Second, C#
arrays are "zero indexed". This means the first element is always at position
0 , the next is at 1 , the next at 2 , and so on. For the MyObjects three-element
array, each element can be accessed with MyObjects[0] , MyObjects[1] ,
and MyObjects[2] . Notice that the last element is 2 and not 3 .
Lines 18 and 19 : Elements 1 and 2 of the MyObjects array are populated
with objects using the function GameObject.Find . This searches the active
scene for game objects with a specified name (case sensitive), inserting a
reference to them at the specified element in the MyObjects array. If no
object of a matching name is found, then null is inserted instead.
More information on arrays and their usage in C# can be found online at
http://msdn.microsoft.com/en-GB/library/9b9dty7d.aspx .
Loops
Loops are one of the most powerful tools in programming. Imagine a game where
the entire level can be nuked. When this happens, you'll want to destroy almost
everything in the scene. Now, you can do this by deleting each and every object
individually in code, one line at a time. If you did this, then a small scene with only
a few objects would take just a few lines of code, and this wouldn't be problematic.
However, for larger scenes with potentially hundreds of objects, you'd have to write
a lot of code, and this code would need to be changed if you altered the contents of
the scene. This would be tedious. Loops can simplify the process to just a few lines,
regardless of scene complexity or object number. They allow you to repeatedly
perform operations on potentially many objects. There are several kinds of loops
in C#. Let's see some examples.
The foreach loop
Perhaps, the simplest loop type in C# is the foreach loop. Using foreach , you can
cycle through every element in an array, sequentially from start to end, processing
each item as required. Consider the following code sample 1-6; it destroys all
GameObjects from a GameObject array:
01 using UnityEngine;
 
Search WWH ::




Custom Search