Creating Prefabs

When you are working with Unity and need to instantiate a game object clone at runtime, you can take advantage of Prefabs. Prefabs are game object templates that can be configured however you like with regard to shape, material, behavior, and anything else you may need. These templates can then be saved in your project. Whenever you need that prefab in the game scene at runtime, you can use a function called Instantiate() that takes a prefab as a parameter and puts it in the game. The following recipe shows how to create Prefabs in Unity.

Getting ready

Start a new scene in your project and follow the instructions.

How to do it...

To make a prefab you first need to create a GameObject. Once you put everything you need into the GameObject, you can save it as a prefab.

  1. Create a new GameObject in the scene, Cube. You should know by now how to do it.
  2. Add the material called checker to Cube by dragging the material from the Project panel onto the object in the scene or into the Material slot in the Hierarchy (with the cube selected in the Hierarchy). You can refer to the following screenshot:
    How to do it...
  3. In the Assets folder of your project, create a new folder and name it Prefabs. Creating a folder is like creating any other type of asset: right-click on the Assets folder and from the menu, select Folder under Create.
  4. Select the Prefab folder and right-click on it to create a new Prefab, as shown in the following screenshot:
    How to do it...
  5. Name the Prefab back_prefab.
  6. Check whether the cube in the scene is at the 0,0,0 position and with 0,0,0 rotation; then, drag it from Hierarchy into back_prefab in the Project panel, as shown in the following screenshot. If you did things right, the small square icon of back_prefab should turn from gray to light blue.
    How to do it...
  7. back_prefab is now ready to be instantiated at will in our game level. You can delete the cube from the scene, as we don't need it anymore and in the Inspector, check whether back_prefab is actually a cube with a checkered material, as shown in the following screenshot:
    How to do it...

How it works...

The procedure to make prefabs is always the same, regardless of the actual characteristics of the game asset itself: create a game object in the scene, add anything you want/need/like to it to define its graphic aspect and behavior, then drag the game object onto a prefab and delete the game object from the scene. Voilà!

The prefab to be used for the background is ready, so we now need to script its behavior to use it for the prototype. This is what we will do in the next recipe.

..................Content has been hidden....................

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