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:
现在我们仅需要创建预制品,在编辑器里做,方法如下:
在项目视图了,修改你的新的预制品的名字为“Brick”
在层次里拖动你创建的立方体到项目视图里的“Brick”上
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".
我们已经创造了我们砖的预制品,所以现在我们必须附加它到我们的脚本里的cube的变量上。选择包含脚本的空GameObject。注意到一个新的变量已经出现在检视器里,称为“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.