2014-08-14 19:47:13|?次阅读|上传:huigezrx【已有?条评论】发表评论

关键词:Unity3D, 游戏, 虚拟现实|来源:唯设编程网

If you execute that code, you will see an entire brick wall is created when you enter Play Mode. There are two lines relevant to the functionality of each individual brick: the CreatePrimitive() line, and the AddComponent() line. Not so bad right now, but each of our bricks is un-textured. Every additional action to want to perform on the brick, like changing the texture, the friction, or the Rigidbody mass, is an extra line.

如果你执行那个代码,你将看到完整砖墙被创建当你进入播放模式时。有两条线关联的每个个个的功能函数:CreatePrimitive() 线和AddComponent() 线。没那么糟糕,每个动作都要执行的砖,如改变纹理、摩擦、或刚体质量,是一个额外的线。

If you create a Prefab and perform all your setup before-hand, you use one line of code to perform the creation and setup of each brick. This relieves you from maintaining and changing a lot of code when you decide you want to make changes. With a Prefab, you just make your changes and Play. No code alterations required.


If you're using a Prefab for each individual brick, this is the code you need to create the wall.


var cube : Transform;

function Start () {

    for (var y = 0; y < 5; y++) {

        for (var x = 0; x < 5; x++) {

            var cube = Instantiate(cube, Vector3 (x, y, 0), Quaternion.identity);




This is not only very clean but also very reusable. There is nothing saying we are instantiating a cube or that it must contain a rigidbody. All of this is defined in the Prefab and can be quickly created in the Editor.


Now we only need to create the Prefab, which we do in the Editor. Here's how:


  1. Choose GameObject->Create Other->Cube  选择GameObject->Create Other->Cube
  2. Choose Component->Physics->Rigidbody  选择Component->Physics->Rigidbody
  3. Choose Assets->Create Prefab  选择 Assets->Create Prefab
  4. In the Project View, change the name of your new Prefab to "Brick"


  1. Drag the cube you created in the Hierarchy onto the "Brick" Prefab in the Project View


  1. With the Prefab created, you can safely delete the Cube from the Hierarchy (Delete on Windows, Command-Backspace on Mac) 利用已创建的预制品,你可以安全的删除这个立方体从层次里(在windows上按 Delete键,在Mac上 按Command-Backspace 键)

We've created our Brick Prefab, so now we have to attach it to the cube variable in our script. Select the empty GameObject that contains the script. Notice that a new variable has appeared in the Inspector, called "cube".


This variable can accept any GameObject or Prefab这个变量可以接受任何GameObject或预制品

Now drag the "Brick" Prefab from the Project View onto the cube variable in the Inspector. Press Play and you'll see the wall built using the Prefab. 现在从项目视图里拖拽"Brick"预制品到检视器里的cube变量上。按播放键你就会看到墙上使用预制品。

This is a workflow pattern that can be used over and over again in Unity. In the beginning you might wonder why this is so much better, because the script creating the cube from code is only 2 lines longer.

发表评论0条 】