Unity crash (forLoop)

I am trying to Instantiate a Tile based map similar to CivilizationIV.

…using for loops to instantiate one row after another and is causing unity to crash!?

Do i need a yield statement in there or something like that?


using UnityEngine;
using System.Collections;

public class WorldBuilder : MonoBehaviour {

public int mapSizeX = 256;
public int mapSizeY = 256;
public GameObject tile_desertPlains;
public GameObject tile_grassPlains;

void Start () {
	BuildMap();	
}

void BuildMap () {
	int tmpX = 0;
	int tmpY = 0;
	
	for(tmpY = 0; tmpY < mapSizeY; tmpY++)
	{
		for(tmpX = 0; tmpX < mapSizeX; tmpX++)
		{
		//Build row 01
			Instantiate(tile_desertPlains, new Vector3(tmpX * 10, 0, tmpY * 10) ,Quaternion.identity);
		}
	}
}

}

You are trying to instantiate 256*256=65536 objects in the same frame. I think Unity does have some protection against that.

Try using a yield statement after each row:

void Start()
{
    StartCoroutine(BuildMap);
}

IEnumerator BuildMap()
{
    int tmpX = 0;
    int tmpY = 0;

    for(tmpY = 0; tmpY < mapSizeY; tmpY++)
    {
        for(tmpX = 0; tmpX < mapSizeX; tmpX++)
        {
            //Build row 01
            Instantiate(tile_desertPlains, new Vector3(tmpX * 10, 0, tmpY * 10) ,Quaternion.identity);
            yield return null;
        }
    }
}

But still. 65536 objects seems to be much too many.

You can’t do that–with a size of 256 * 256, it’s over 65K separate objects, which is far far too many. You will need to build meshes which contain a number of combined tiles, say 32 * 32 (maybe more or less, depending on how detailed the tiles are).