- Home /
Spawning A Grid Of Cubes
I am using the following script to spawn a grid of cubes in my scene the problem is while its spawining if you move the screen it throws the cubes all over the place. Also if you change the worldWidth or Height for the first time you press play it places the first cube in the wrong place.
using UnityEngine;
using System.Collections;
public class WorldSpawn : MonoBehaviour {
public GameObject block1;
int worldWidth = 10;
int worldHeight = 10;
float spawnSpeed = 0;
void Start ()
{
StartCoroutine(CreateWorld());
}
IEnumerator CreateWorld (){
for(int x =0; x<worldWidth; x+=1) {
yield return new WaitForSeconds(spawnSpeed);
for(int z =0; z<worldHeight; z+=1) {
yield return new WaitForSeconds(spawnSpeed);
GameObject block = Instantiate(block1,block1.transform.position, block1.transform.rotation)as GameObject;
block1.transform.position = new Vector3(transform.position.x + x, transform.position.y, transform.position.z + z);
}
}
}
}
Let me guess, this script is attached to the camera, isn't it?
Ok, let me post a changed version of your script then, and see if it works for you or not.
Answer by DavidDebnar · Jul 10, 2013 at 07:35 PM
Ok, try this fixed version of your code.
using UnityEngine;
using System.Collections;
public class WorldSpawn : MonoBehaviour {
public GameObject block1;
public int worldWidth = 10;
public int worldHeight = 10;
public float spawnSpeed = 0;
void Start () {
StartCoroutine(CreateWorld());
}
IEnumerator CreateWorld () {
for(int x = 0; x < worldWidth; x++) {
yield return new WaitForSeconds(spawnSpeed);
for(int z = 0; z < worldHeight; z++) {
yield return new WaitForSeconds(spawnSpeed);
GameObject block = Instantiate(block1, Vector3.zero, block1.transform.rotation) as GameObject;
block.transform.parent = transform;
block.transform.localPosition = new Vector3(x, 0, z);
}
}
}
}
--David--
Answer by tw1st3d · Jul 10, 2013 at 07:29 PM
Well considering you're returning
yield return new WaitForSeconds(spawnSpeed);
After 0 seconds, it's not going to continue after that.
return
Means to finish the method.
No. That's not the cause, and he said that the blocks spawn, but at wrong position.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Object Spawning Too Low 0 Answers
Setting Spawn Rotation correct 1 Answer
Spawning off size blocks 1 Answer
Distribute terrain in zones 3 Answers