Hour 12. Prefabs


What You’ll Learn in This Hour:

• The basics of prefabs

• How to work with custom prefabs

• How to instantiate prefabs in code


A prefab is a complex object that has been bundled up so that it can be recreated over and over with little extra work. In this Hour, you will be learning all about prefabs. You will star by learning all about prefabs and what they do. From there you will learn how to create prefabs in Unity. You will learn about the concept of inheritance. You will finish by learning how to add prefabs to your scene both through the editor and through code.

Prefab Basics

As mentioned above, a prefab is a special type of asset that bundles game objects up. Unlike simply nesting objects in the hierarchy view, a prefab exists in the project view and can be reused over and over across many scenes. This allows you to build complex objects, like an enemy, and use it to build an army. You can also create prefabs with code. This allows you to generate a nearly infinite amount of objects during run time.


Note: Thought Exercise

If you are having trouble understanding the importance of prefabs, consider this: last hour you made the game Chaos Ball. When making that game, you had to make a single chaos ball and duplicate it four more times. What if you wanted to make more chaos balls on the fly during run time? The fact is that you couldn’t. Not without prefabs anyway. Now what if you had a game that used an “orc” enemy type? Again, you could set a single orc up and then duplicate it many times, but what if you wanted to use the orc again in another scene? You would have to completely remake the orc in the new scene. If the orc was a prefab though, it would be a part of the project and could be reused again in any number of scenes. Prefabs are an important aspect of Unity game development.


Prefab Terminology

There are some terms that are important to know when working with prefabs. If you are familiar with the concepts of Object Oriented Programming practices, you may notice some similarities:

Prefab: the Prefab is the base object. This exists only in the project view. Think of it as the blueprint.

Instance: An actual object of the prefab in a scene. If the prefab is a blueprint for a car, then an instance is an actual car. If an object in the scene view is referred to as a “prefab”, it is really meant that it is a “prefab instance”. The phrase “instance of a prefab” is synonymous with “object of a prefab”.

Instantiate: The process of creating an instance of a prefab. It is a verb and is used like: “I need to instantiate an instance of this prefab.”

Inheritance: This does not mean the same thing as standard programming inheritance. In this case, the term inheritance refers to the nature by which all instances of a prefab are linked to the prefab itself. This will get covered in greater detail later this hour.

Prefab Structure

Whether you know it or not, you have already worked with prefabs. Unity’s character controller is a prefab. To instantiate an object of a prefab into a scene, you only need to click and drag it into place in the scene view or hierarchy view (see Figure 12.1).

Figure 12.1. Add a prefab instance to a scene.

Image

When looking at the hierarchy view, you can always tell which objects are instances of prefabs because they will appear blue (see Figure 12.2). Just as with non-prefab complex objects, complex instances of prefabs also have an arrow that allows you to expand them and modify the objects inside.

Figure 12.2. Prefab instances appear blue in the hierarchy view.

Image

Since a prefab is an asset that belongs to a project and not a particular scene, you edit the prefab in the project view. Just like game objects, prefabs can be complex. Editing the children elements of the prefab is done by clicking the arrow on the right hand side of the prefab (see Figure 12.3). Clicking this arrow will expand out the object for editing. Clicking again will condense the prefab again.

Figure 12.3. Expanding the contents of a prefab in the project view.

Image

Working with Prefabs

Using Unity’s built in prefabs is nice, but often you will want to create your own. Creating a prefab is a two-step process. The first step is the creation of the prefab asset. The second step is filling the asset with some content.

Creating a prefab is really easy. Like all other assets, you will want to start by creating a folder under “Assets” in the project view to contain them. Then, simply right click on the newly created folder and select “Create->Prefab” (see Figure 12.4). A new prefab will appear which you can name whatever you’d like. Since the prefab is empty, it will appear as an empty white box.

Figure 12.4. Creating a new prefab.

Image

The next step is to fill the prefab with something. Any game object can go into a prefab. You simply need to create the object once in the scene view and then click and drag it onto the prefab asset.

Adding a Prefab Instance to a Scene

Once a prefab asset is created, it can be added as many times as you’d like to a scene or any number of scenes in a project. To add a prefab instance to a scene all you need to do is click and drag the prefab from the project view into place in the scene view. You will notice that when placing prefab instances into the scene, the instance can easily be placed on top of other objects. This makes positioning the new instances very simple.

Inheritance

When the term inheritance is used in conjunction with prefabs, it means the link by which the instances of a prefab are connected to the actual prefab asset. Simply put, if you change the prefab asset, all objects of the prefab are also automatically changed. This is incredibly useful. More often than not, you will put a large number of prefab objects into a scene only to realize that they all need a minor change. Without inheritance, you would have to change each one independently.

There are two ways in which you can change a prefab asset. The first is by making changes in the project view. Simply selecting the prefab asset in the project view will bring up its components and properties in the inspector view. If you need to modify a child element, you can expand the prefab (described above) and change those objects in a similar fashion.

Another way you can modify a prefab asset is to drag an instance into the scene. From there, you can make any major modifications you would like. When finished, simply drag the instance back onto the prefab asset to update it.

Breaking Prefabs

Sometimes you will need to break a prefab instance’s link to the prefab asset. You may want to do this if you need an object of the prefab, but you don’t want the object to change if the prefab ever changes. Breaking an instance’s link to the prefab does not change the instance in any way. It still maintains all of its objects, components, and properties. The only difference is that it is no longer an instance of the prefab and therefore is no longer affected by inheritance.

To break and object’s link to the prefab asset, simply select the object in the hierarchy view. Once selected, click “GameObject->Break Prefab Instance”. You will notice that the object does not change, but its name turns from blue to black. Once the link is broken, it cannot be re-applied.

Instantiating Prefabs through Code

Placing prefab objects into a scene is a great way to build a consistent and planned level. Sometimes, however, you want to create instances at run time. Maybe you want enemies to respawn, or you want them to be randomly placed. It is also possible that you need so many instances that placing them by hand isn’t feasible. Whatever the reason, instantiating prefabs through code is a good solution.

There are two ways to instantiate prefab objects in a scene and they both use the Instantiate() method. The first way is to use Instantiate() like this:

Instantiate(GameObject prefab);

As you can see, this method simply reads in a game object variable and makes a new object of it. The location, rotation, and scale of the new object are the same as the prefab in the project view. The second way to use the Instantiate() method is like this:

Instantiate(GameObject prefab, Vector3 position, Quaternion rotation);

This method requires three parameters. The first is still the object to make a copy of. The second and third parameters are the desired position and rotation of the new object. You may have noticed that the rotation is stored in something called a “Quaternion”. Just know that this is how Unity stores rotation information. The true application of the Quaternion is beyond the scope of this hour. An example of the two methods of instantiating objects in code can be found in the exercise at the end of this Hour.

Summary

This hour you learned all about prefabs in Unity. You started by learning the basics of prefabs: the idea, the terminology, and the structure. From there, you learned to make your own prefabs. You explored how to create them, add them to a scene, modify them, and break them. Finally, you learned to instantiate prefabs objects through code.

Q&A

Q. Prefabs seem a lot like classes in Object Oriented Programming (OOP). Is that accurate?

A. Yes, there are many similarities between classes and prefabs. Both are like blueprints. Objects of both are created through instantiation. Objects of both are linked to the original.

Q. How many objects of a prefab can exist in a scene?

A. As many as you would like. Be aware though that after you get above a certain amount, the performance of the game will be impacted. Every time you create an instance, it is permanent until destroyed. Therefore, if you create 10,000, there will be 10,000 just sitting in your scene.

Workshop

Take some time to work through the questions here to ensure you have a firm grasp on the material.

Quiz

1. What is the term for creating an instance of a prefab asset?

2. What are the two ways to modify a prefab asset?

3. What is inheritance?

4. How many ways can you use the Instantiate() method?

Answers

1. Instantiation.

2. You can modify a prefab asset through the project view or by modifying an instance in the scene view and dragging it back onto the prefab asset in the project view.

3. It is the link that connects the prefab asset to its instances. It basically means that when the asset changes, the objects change as well.

4. Two. You can specify just the prefab or you can also specify the position and rotation.

Exercise

In this exercise you will get a chance to work once again with the prefab you made earlier this hour. This time you will get to instantiate objects of the prefab through code and hopefully have some fun with it. The complete project for this exercise can be found in the book assets for Hour 12 named “Hour12_Exercise”.

1. Create a new scene in the same project the lamp prefab is in. Click the “Lamp” prefab in the project view and give it a position of (-1, 1, -5).

2. Add an empty game object to your scene. Rename the game object “SpawnPoint” and position it at (1, 1, -5). Add a plane to your scene and position it at (0, 0, -4) with a rotation of (270, 0, 0).

3. Add a script to your project. Name the script “PrefabGenerator” and attach it to the spawn point object. Listing 12.1 has the complete code for the prefab generator script:

Listing 12.1. PrefabGenerator.cs


using UnityEngine;
using System.Collections;

public class PrefabGenerator : MonoBehaviour {
    //We will store a reference to the target prefab from the inspector
    public GameObject prefab;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //Whenever we hit the B key, we will generate a prefab at the
        //position of the original prefab
        //Whenever we hit the space key, we will generate a prefab at the
        //position of the spawn object that this script is attached to
        if(Input.GetKeyDown(KeyCode.B))
            Instantiate(prefab);

        if(Input.GetKeyDown(KeyCode.Space))
            Instantiate(prefab, transform.position, transform.rotation);
    }
}


4. Run the scene. Notice how pressing the ‘B’ button creates a lamp at its default prefab position while pressing the space bar creates an object at the spawn point. Also notice how the prefabs collide with each other causing some unique interactions.

You may notice while running this scene that the lamps created continue to fall forever and never disappear from the scene. As a bonus challenge, see if you can create a plane with a trigger below the scene that will destroy the lamps when they enter. This way, the game cleans up the lamps no longer visible and the game has no long term performance issues as a result.

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

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