Asteroids – Prefabs
Did you work out how we could simplify our if statements from last time? Here is the answer:
We can just put != 0 (does not equal zero) because we use the value of the axes in our calculations. This means it does not matter if it is greater than zero or less than zero, it just matters if it is not zero.
Anyway, on with the tutorial…
Now we can move our ship around we should add some asteroids to the scene. For the purpose of this tutorial we will be using a primitive sphere.
Add a sphere to unity by right clicking on the hierarchy, select the 3D Object option and then the Sphere option.
Rename this Asteroid in the hierarchy and change its transform so it is somewhere nice in the scene.
Now in our assets folder make a new folder called prefabs.
Drag the asteroid object from the heirarchy into this folder. Notice how the asteroid object name now appears blue in the hierarchy, this means it is a prefab.
What is a prefab? A prefab is an object (or group of objects) which are saved in the assets folder. This allows us to change things on one of the objects and apply the change to all the same objects. This is especially useful for objects which have many copies within the scene.
It also makes it easier for us to create the objects at run time as you will see in the next part of the tutorial.
For now we need to make a new script called AsteroidManager and add it to the asteroid object. Click the apply button after adding the script.
Lets duplicate the asteroid object so that there are now 3 in the scene. To duplicate either right click on the asteroid object and select duplicate or drag the prefab from the prefabs folder until there are 3 in the scene.
Move the other two asteroids so they are in a different place to the original one in the scene.
Next select one of the asteroids (any one) and add a rigid body component to it by clicking the add component button and searching for it. Turn gravity off and press the apply button again. Notice how the rigid body is now on all three asteroids.
That concludes this part of the tutorial. Next time we will look at instantiating and object in the scene.