Game Development Reference
In-Depth Information
Save the script and play. When you press the D key, the sphere is immediately destroyed. But
wait, you say, I missed something. You cleverly used +' to skim the Destroy() function scripting
reference and noticed that it can take an optional second float parameter that represents a built-in
time delay.
Change the line Destroy(gameObject); to Destroy(gameObject, 2); . Save and play to demonstrate
that there is now a two-second delay after you press the D key before the sphere is destroyed. Using
this parameter instead of our previous code to create a time delay reduces the total number of lines
of code needed to accomplish the same goal.
There is often more than one way to get the same result. Keep your eyes open and don't hesitate to
refactor your code when you find a more effective solution.
Instantiation
So far you've gone through the complete lifecycle of a game object from the start of the game,
determining its behavior during gameplay by writing code to modify, enable and disable game object
components.
You learned to destroy the game object at runtime, but not to create one. Throughout these examples
you used a sphere game object that was created and positioned in the scene prior to runtime.
Instantiate() is particularly useful for creating duplicates of game objects. What are game object
duplicates? Prefabs! You know a prefab is a blueprint of a game object. Instantiation is the process
of creating a copy of a game object from this blueprint, called an instance .
From the Hierarchy view, drag the Sphere into the Prefabs folder in the Project panel. You'll see a
new Sphere prefab appear next to the Pink Rose Cube prefab. Delete the Sphere from the Scene
view by selecting it in the Scene or Hierarchy view then selecting Edit ➤ Delete from the editor top
menu. Again using the editor top menu, select GameObject ➤ Create Empty. The empty game
object's Translate gizmo will appear in the Scene view.
In the Project panel, select the Scripts folder, then in the control bar select Create ➤ Javascript and
name the new script CreateSpheres. Drag the script icon to the empty GameObject in the Hierarchy
view to attach it. The CreateSpheres script should appear in the Inspector as a new component of
the empty game object (Figure 4-17 ).
 
Search WWH ::




Custom Search