Using prefabs

In the previous section, you created a sphere to simulate a blood droplet. You also created a red material and applied it to your sphere. In the game, we might want to simulate a great battle and have multiple blood droplets visible at once. In Unity, we can make as many copies of our master as we want. For example, let's assume we have 100 spheres, all copied from our master. What happens when we want to alter them, perhaps changing the size or material? It would be a laborious task to edit each one. 

An alternative is to use a prefab. In Unity, a prefab is an asset type that serves as a shell for a GameObject along with properties and components. The sphere we created is a GameObject, and, as you can see in the following screenshot, our sphere has several components and properties: 

So, let's create a prefab to hold our sphere. Follow these steps:

  1. In the Project panel, select the Prefabs folder.
  2. Right-click on the Prefabs folder and select CreatePrefab. Alternatively, you could have selected, from the top menu, Assets | Create | Prefab.
  3. Name the prefab bloodDroplet. You will notice that there are no components or properties visible in the Inspector panel for the new prefab.
  4. Next, drag the Sphere GameObject from the Hierarchy panel to the new bloodDroplet prefab in the Project panel. Now, when you view the prefab in the Inspector panel, you can see the components and properties that our sphere had.
  5. We no longer need the original sphere, so delete that in the Hierarchy panel. 

Now that we have a bloodDroplet prefab, we can drag it into our scene as many times as we want. We can also add them to our scene using scripts. 

To experience the power of prefabs in Unity, try the following:

  1. Select the bloodDroplet prefab in the Project panel.
  2. Drag several copies of the bloodDroplet prefab into your scene.
  3. In the Inspector panel, change the color. You will notice that all the bloodDroplets in your scene were changed based on the change you made to the prefab.
  4. Return the color of the prefab to the red material.
  5. Delete any bloodDroplets from your scene. This is most easily done in the Hierarchy panel.
Deleting the bloodDroplets from your scene does not remove all bloodDroplets from your game. Because we have the bloodDroplet prefab, we can add bloodDroplets to our scene at any time. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset