- Home /
Instantiate loading very slowly
I am trying to set up a basic map with 256x256. However the load time is astronomical. I've tried reducing the size of the array but it is still way slower than it needs to be. What have I done wrong?
var mapSizeX = 256; var mapSizeZ = 256; var mapArray = MultiDim.StringArray(mapSizeX, mapSizeZ); var createMap : Transform;
function Start () {
for (var x = 0; x < mapSizeX; x++) {
for (var z = 0; z < mapSizeZ; z++) {
mapArray[x,z] = (x) + " " + (z);
var pos = Vector3 (x, 0, z);
var objecta = Instantiate(createMap, pos, Quaternion.identity);
objecta.name = mapArray[x,z];
}
}
}
Answer by unitynoob · Nov 10, 2010 at 06:55 AM
Firstly Instantiate is a slow function that you may want to reduce usage in a big nested loop, and how slow it is depends on how complicated the object it is instantiating. Instantiating a cube is much faster than a monster with rigidbody, collider and a couple of scripts.
Secondly you may try to reduce to 'new' a variable in a loop. Reuse them, namely 'pos' and 'objecta' in your loop.
Lastly if you do not need your map be ready in a frame, you may spread the instantiations across frames in loops by 'yield', such that you can reduce the degree of lagging.
Answer by Eric5h5 · Nov 10, 2010 at 08:01 AM
256*256 = 65,536 objects, which is way way more than you would ever want. You should reduce that by a couple orders of magnitude. For such a large map, you'd be better off constructing it as a series of meshes using the Mesh class, where each mesh would cover, say, 64x64 squares. This is a quite a bit more complicated than just instantiating prefabs, but Unity can't feasibly handle tens of thousands of separately instantiated objects like that. Another possibility, depending on what you're doing, is to instantiate only the map immediately around the player, and remove the squares that are out of view.
Answer by soulburner · Nov 20, 2012 at 02:51 AM
Consider re-using objects that moved off screen instead of killing and instantiating new ones