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.
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.
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.back_prefab.
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.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: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.
18.191.189.186