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);
 
      }
 
      }
 
      }
}

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–

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.