Introducing Randomness
One of the great things about games is never knowing what to expect. Out of a number of possibilities, only one
will be chosen to occur at any given time. In the next part of creating the rockfall, you will use the Random function,
to determine which of four different rocks to drop into the scene.
For that, you will need a few more rocks.
1. Create two more new rock prefabs, Rock2 and Rock3, using scale and rotation to make
them different from the first two.
2. Rename the Rock Prefab to Rock0 in the Project view.
3. Move all of the rocks up to about the same spot as Rock1 and Update all of the prefabs.
4. Delete all of the new rocks from the scene.
5. Close the Rocks script.
6. Rename it in the Project view to Rockfall.
And, yes, you could also rename it in the script editor, but then the original would still be around.
1. Open it again.
2. Replace var prefab : Transform with the following to hold the various Rocks:
var rocks : GameObject[]; // create an array to hold the rocks
Because the array will be loaded in the Inspector, and you may decide you want to create more than four different
rocks, you will want another variable to keep track of the number of elements in the array.
3. Create another variable to hold the length of the array:
internal var arrayLength : int; // var to hold number of elements in the array
4. Create a Start function and assign the number of elements:
function Start () {
arrayLength = rocks.length; // number of elements in the array
}
5. Change the Instantiate line to:
Instantiate (rocks[0]);
You will start by testing just the Element 0 rock.
6. Save the script.
7. Select the Rock Zone object in the Hierarchy view and set the Rock array Size to 4.
8. Load each of the rock prefabs into the elements.
9. Click Play and drive the First Person Controller back and forth to drop the rock ove