- Home /
 
Custom prefabed spawner
Im using this script to generate my floor created with cubes, currently with primitives, but I would like it to use a custom prefab as the cube? How:
 for (var y = -9; y < 10; ++y)
 for (var x = -9; x < 10 ++x)
 for (var z = -4; z < 5; ++z) {
     var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
     cube.transform.position = transform.position + Vector3(x, 0, y);
 }
 
              
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by robertbu · Mar 20, 2013 at 03:54 PM
At the top of your file put:
 var prefab : GameObject;
 
               Change your code:
 for (var y = -9; y < 10; ++y)
 for (var x = -9; x < 10 ++x)
 for (var z = -4; z < 5; ++z) {
 var go = Instantiate(prefab, transform.position + Vector3(x, 0, y), Quaternion.identity);
 }
 
               Select the object this script is attached to in the hierarchy. Then in the inspector, drag and drop the prefab onto the prefab variable.
Answer by Yokimato · Mar 20, 2013 at 03:56 PM
Instead of calling the CreatePrimitive method, you can replace it by calling Instaniate. Here's an example:
 // JavaScript
 
 // Instantiates a prefab in a grid
 
 var prefab : GameObject;
 var gridX = 5;
 var gridY = 5;
 var spacing = 2.0;
 
 function Start () {
     for (var y = 0; y < gridY; y++) {
         for (var x=0;x<gridX;x++) {
             var pos = Vector3 (x, 0, y) * spacing;
             Instantiate(prefab, pos, Quaternion.identity);
         }
     }
 }
 
               You can see this in more detail (along with other ways to progamatically create objects) at the official unity API: http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html
Your answer