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

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

Unity Manual > User Guide > Creating Gameplay > Instantiating Prefabs at runtime


By this point you should understand the concept of Prefabs at a fundamental level. They are a collection of predefined GameObjects & Components that are re-usable throughout your game. If you don't know what a Prefab is, we recommend you read the Prefabs page prior to this one.


Prefabs come in very handy when you want to instantiate complicated GameObjects at runtime. The alternative to instantiating Prefabs is to create GameObjects from scratch using code. Instantiating Prefabs has many advantages over the alternative approach:


  • You can instantiate a Prefab from one line of code, with complete functionality. Creating equivalent GameObjects from code takes an average of five lines of code, but likely more.
  • 你可以用一行代码初始化,利用完成的功能。从代码可以创造同等GameObjects需要平均5行代码,但可能更多。
  • You can set up, test, and modify the Prefab quickly and easily in the Scene and Inspector.
  • 你可以在场景里及检视器里迅速并容易的设置,测试及修改预制品。
  • You can change the Prefab being instanced without changing the code that instantiates it. A simple rocket might be altered into a super-charged rocket, and no code changes are required.
  • 你可以修改预制品在初始化时不需要修改代码而初始化它。一个简单的火箭可能会改变成超级火箭,并没有代码需要改变。

Common Scenarios 常见方案

To illustrate the strength of Prefabs, let's consider some basic situations where they would come in handy:


  1. Building a wall out of a single "brick" Prefab by creating it several times in different positions.


  1. A rocket launcher instantiates a flying rocket Prefab when fired. The Prefab contains a Mesh, Rigidbody, Collider, and a child GameObject with its own trail Particle System.


  1. A robot exploding to many pieces. The complete, operational robot is destroyed and replaced with a wrecked robot Prefab. This Prefab would consist of the robot split into many parts, all set up with Rigidbodies and Particle Systems of their own. This technique allows you to blow up a robot into many pieces, with just one line of code, replacing one object with a Prefab.


Building a wall 创建一个墙

This explanation will illustrate the advantages of using a Prefab vs creating objects from code.


First, lets build a brick wall from code: 首先,让我们从代码创建一个砖头墙:

function Start () {

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

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

            var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);


            cube.transform.position = Vector3 (x, y, 0);



  • To use the above script we simply save the script and drag it onto an empty GameObject.
  • Create an empty GameObject with GameObject->Create Empty.
  • 使用上面的脚本我们单独保存这个脚本并拖拽它到一个空白的GameObject上。建立一个空白的脚本利用GameObject->Create Empty
发表评论0条 】