I am sorry for this question because I do see a lot of threads talking about it alot and I tried to understand them but I am unable to get my script working after about 2 days of brain thumping. I am trying to simply instantiate a number of prefabs or objects within a parent that is moving so the instantiated objects move with the parent. I am also using this random instantiate and would also like to only spawn a limited amount of prefabs or objects in this area I have specified. If I do function Start it will only spawn one object.
Thank you,
Scott
Here is my script. The parent obect name is “test”
var prefab:Transform;
function Update ()
{
var position = Vector3(Random.Range(-150, -50), -20, Random.Range(100,2000));
Instantiate(prefab, position, Quaternion.identity);
prefab.transform.parent = test.transform;
}
Ok - Your tip got me a lot closer to what I need.
This Script will instantiate a Brick wall and parent it to the empty object it is attached to and if the empty is moving it will move.
This is exactly what I want to do but instead of a brick wall a grid like the script after this below that does not parent properly.
Here is the Brick Wall that works correctly and all the clones become children of the empty parent it is attached to:
var cube : Transform;
function Start () {
for (var y = 0; y < 5; y++) {
for (var x = 0; x < 10; x++) {
var cube = Instantiate(cube, Vector3 (x, y, 0), Quaternion.identity);
cube.transform.parent = transform;
}
}
}
Here is my Grid Script that does not work. The Clones do not become children of the empty parent:
Does anyone know how to make this work as nicely as the brick wall script above?
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);
prefab.transform.parent = transform;
}
}
Ok I figured it out ! Woo Hoo! Gosh that feels good!
I had to define var prefab a second time before parent. - var prefab = Instantiate(prefab, pos, Quaternion.identity);
Here is the working script that will create a grid of clones parented to the empty this script is attached to.
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;
var prefab = Instantiate(prefab, pos, Quaternion.identity);
prefab.transform.parent = transform;
}
}
}
Thank you for your reply. That does make it create 1 child to the parent but all the (Clones) remain outside of the parent. Is there a line of code that is missing? I tried using prefabClone.transform.parent = transform; but that just gives me errors.