Unity 3.2 uses presets (PREFAB) to make reusable components

Source: Internet
Author: User

Categories: Unity, C #, VS2015

Date Created: 2016-04-02 I. INTRODUCTION

A prefab (Prefab, also known as a preset) is a special resource that is stored in the project view, and is a reusable game object (Gameobject) container.

If you have multiple preforms (Prefab) in project, you can save them all to the Prefabs subfolder of the Assets folder in Project view for easy lookup.

All preforms under the Prefabs subfolder can be placed into multiple scenes, and can still be used multiple times even in the same scene.

Adding a prefab to a scene is the creation of an instance of the precast body. Also, because instances of all the preforms in the scene are automatically linked to the original preform (Prefab) in project, these instances are essentially clones of the original preform. Or, no matter how many prefab instances there are in the scene, as long as you make any changes to one of the prefab in project, you will see that the changes are immediately applied to all instances of that prefab in the scene.

1. Creating a Preform (Prefab) in Project View (project)

To create a prefab (Prefab) in project, simply drag and drop one of the game objects (Gameobject) you created in the scene to a Prefab in the project view.

If the name of the game object (Gameobject) in the Hierarchy view (Hierarchy) turns blue, it means that the object in Hierarchy is an instance of a prepared prefab. At this point, you can decide whether to keep this instance in the hierarchy view (Hierarchy) or delete the instance, as needed, without affecting the original prefab that was created in project, regardless of if you keep it.

2. Create an instance of the preform in the Hierarchy view (Hierarchy)

To create an instance of a prefab in the current scene, drag a prefab directly from the Project view (Project views) to the scene or hierarchy view (Hierarchy).

The "blue" font in the hierarchy view indicates that the object is an instance of a prefab.

Once you have created an instance of the prefab, the instance is automatically linked to the source prefab in project and displayed in the Hierarchical View (Hierarchy) as "blue" text.

In this case, 3 of the game objects are blue, indicating that this is an example of a prefab.

3. Operation of the precast body in the viewer (Inspector)

(1) Meaning of bold

Sometimes you may want to change only the properties of a single prefab instance, while maintaining a complete link to the source preform, you can see that the variable name that corresponds to the instance becomes bold, indicating that the variable has been overridden. Note that all overridden properties are not affected by the source preform change.

(2) Select

If you selected a prefab instance and want to affect all instances of your changes, you can click the Select button directly in the Viewer (Inspector) to select the original prefab that you changed.

(3) Apply

If you want to update the source preform and all its instances with the overridden value, click the Apply button in the viewer (Inspector). Note that this "app" does not work for "root position" and "rotation" because it affects the absolute position of the instance and causes all instances to be placed in the same location. However, apply will work on the position and rotation of any child or ancestor elements of the root, as they are computed relative to the root transformation.

(4) Revert

If you want to discard all overrides for a particular instance, click the (Revert) button.

4. Import the Precast body

When you put a grid resource under the Assets folder, Unity automatically imports the file and generates something that looks like a prefab outside the grid. However, this is not actually a prefab (Prefab), it is just something that the resource file itself uses.

Note that the resource (asset) icon is slightly different from the preset (Prefab) icon.

A resource is an instance of a game object (Gameobject) that exists in the scene and is linked to the source resource instead of to the prefab (Prefab). You can add and remove components to the game object (Gameobject) normally. But you can't make any changes to the resource itself because it adds data to the resource file itself! If you want to create something reusable, you should make it into a prefab.

When you select a resource instance, the "Apply" button in the viewer (Inspector) is replaced with the "Edit" button. Clicking this button launches the editing application (such as Maya or Max) for the resource. Second, Prefabs basic usage Example

Through the above introduction, you should have learned the concept of prefabs from a basic level: Prefabs is essentially a collection of gameobjects (predefined game objects) and components (component), which is a container object that can be reused in the game.

With prefabs, you can easily instantiate complex gameobjects (game objects) at run time.

1. How to create a game object

In unity, there are two ways to create an object (Game object):

(1) Mode 1: All in C # code implementation. In this way, the game object (Gameobjects) is created and initialized from scratch using C # code.

(2) Mode 2: Use Prefabs to achieve. That is, to make the preform first, and then instantiate the prefab by code at runtime.

Mode 2 (implemented with prefabs) has several advantages over mode 1:

L can instantiate prefab with one line of code and have full functionality. Using code to create an equivalent game object (gameobjects) requires an average of five lines of code and may require more.

L can quickly set, test, and modify precast bodies in scene and viewer (Inspector).

L can change a prefab that has been instantiated without changing the code that instantiates the prefab. For example, you can change a simple rocket into a super rocket, but you don't need to change the code.

2. Example-Create a wall

To illustrate the power of prefabs, let's take a look at some of the basic things that can be prefabs:

(1) in different locations, the use of a single "brick" precast body to create a wall.

(2) When launched, the rocket launcher instantiates a flying rocket preform. The preform is a sub-game object (Gameobject) that contains a mesh, a rigid body (rigidbody), a collider (Collider), and a particle system with its own trailing particle systems.

(3) The robot exploded into many fragments. At this point the complete operating robot has been destroyed and replaced with a broken robotic preform. The preform consists of a plurality of parts of the robot, all with its own rigid body (rigidbodies) and particle system (particle systems). With a prefab, you can replace an object with a specified prefab with just one line of code, causing the robot to explode into many fragments.

The example is simply to illustrate the advantage of using prefab to create objects, and to create objects with prefab, compared to creating objects using code.

(1) Realization Mode 1

Start by demonstrating how to create objects with code, because only comparisons can make sense of the drawbacks of this approach.

Create a subfolder named scripts under assets in the project view of the Ch03demos project, and then add a C # script named Demo1 to the subfolder:

By double-clicking the Demo1 script, unity will automatically start VS2015 and automatically open the Demo1.cs file in VS2015, and the folder structure under assets in Solution Explorer is the same as the folder structure in unity:

Change the Demo1.cs file to the following:

usingUnityengine;usingSystem.Collections; Public classdemo1:monobehaviour{voidStart () { for(inty =0; Y <5; y++)        {             for(intx =0; X <5; X + +) {gameobject cube=gameobject.createprimitive (Primitivetype.cube); Cube. AddComponent<Rigidbody>(); Cube.transform.position=NewVector3 (x, Y,0); }        }    }}

Save the file.

Switch to Unity, choose "Gameobject", "Create empty" from the main menu, and then drag and drop the Demo1 script under the Scripts folder into the empty game object you just added.

Switch to the game view and click the Play button to observe the performance. You'll see a cube wall created entirely in code (the wall will automatically collapse due to the default use of gravity):

Of course, because no textures were added, it was just a white wall (a cube after it collapsed). If you want to perform additional operations, such as changing the quality of brick textures, friction, or rigid bodies, you will need to add additional code to see how cumbersome it can be to achieve this.

Delete the empty game object that you just created in the hierarchy view.

(2) Realization Mode 2

The 2nd way to do this is to create a "wall" preform, and then use the "Create a prefab instance" approach to create multiple walls.

The steps are as follows:

Select the main menu, "Gameobject", "3D Object", "Cube" to create a cube:

At this point, the cube you just created is selected in the hierarchy view.

Drag and drop the Brick_d under the texture folder onto this cube in the hierarchy view.

In Project view, under the Assets folder, add a prefabs subfolder:

Right-click the prefabs subfolder and select "Create", "Prefab":

Change the name of the newly added prefab to "Brick".

Drag and drop the cube you created in the hierarchy view onto the "Brick" that you just created in Project view.

This creates a prefab (or preset) called "Brick".

After you create a preset (Prefab), the cube (cube) that you added in the hierarchy view is not already available, you can select it from the Hierarchy view (Hierarchy), and then press DELETE.

Re-add an empty game object (Gameobject).

In the VS2015 Solution Explorer project, under the Scripts subfolder, add a C # script (Demo2.cs) with the file name Demo2.cs, and then change it to the following:

usingUnityengine;usingSystem.Collections; Public classdemo2:monobehaviour{ PublicTransform Brick; voidStart () { for(inty =0; Y <5; y++)        {             for(intx =0; X <5; X + +) {Instantiate (Brick,NewVector3 (x, Y,0), quaternion.identity); }        }    }}

Press the <F5> key to attach it to unity, and then press <Shift>+<F5> to end.

Switch to unity and drag and drop the script under the drawing view onto the cube you just added, which adds a Demo2 component to the object:

In addition, a new variable named "Brick" will appear in the viewer (Inspector), which can accept any game object (Gameobject) or prefab as a variable of type transform.

From the project view, drag and drop the preform "Brick" to the value of the Brick variable in the viewer (Inspector) view (the function is to create an instance of the prefab as the value of the Brick variable):

Press play to see the walls created with both the Prefab and the C # script:

It can be seen that the script code implemented in this way is not only very clean, but also reusable with this brick prefab.

When you first start learning, you may wonder why it is not more flexible and convenient to create a cube in the 1th way. Why do you have to do another prefab?

This is because with prefab, you can make adjustments to it in a matter of seconds:

    • Want to add or change the quality of all instances? Simply add a rigid body to the preform and adjust the gravity of the rigid body (rigidbody) at once.
    • Want to use a different material (Material) for all instances? Simply drag and drop the material (Material) onto the preform once.
    • Want to change the friction? Using a different physical material (physic Material) in a prefab collider is OK.
    • Want to add a particle system for all cubes (particle systems)? Add a sub-object to the preform once.

Of course, if you just want to learn the operation steps, can not find the Brick_d.jpg file, look for a pair of other. jpg pictures instead of the line, anyway, the goal is to this block of wall with a cube structure to paste full map, understand the meaning of the line.

Unity 3.2 uses presets (PREFAB) to make reusable components

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.