Combine objects instantiated at runtime

I'd like to combine objects to reduce the drawcall amount. Currently it goes to thousands so it's really bad. I'm creating the terrain with the following basecode:

function Start() {
var width:int = 100;
var height:int = 100;
for(i = 0; i < width; i++) {
for(ii = 0; ii < height; ii++) {
Instantiate(Resources.Load("Ground"), Vector3(i,0,ii), Quaternion.Euler(0,0,0));
}

Should I combine the whole thing as one object? They're plain planes just next to each other. I'm planning on using a 1024 x 1024 texture with all the different terrain types and assign it to all planes. Will this approach be any good? 1024 x 1024 is needed considering the amount of different tiles I'll be using.

You better look at how to make a Mesh object as this will give way to many objects. You could try to merge them with the CombineChildren script from Standard Assets, but will probably give quite a delay. Also, instead of `Resources.Load` use a var Transform as global variable and drag the Ground prefab to it. If you use Resources.Load Unity won't know that you're actually using Ground in your project and if you don't have any other direct references to it, will not include it in the build of the project.

If you have only one Ground type it isn't to hard to generate the Mesh with some little coding, if you need help with that, let us know.

If you're using Unity 2.6+ there's a built-in function on Mesh called CombineMeshes that's probably preferable over the standard assets CombineChildren script. See the documentation here: http://unity3d.com/support/documentation/ScriptReference/Mesh.CombineMeshes.html

Some caveats of doing what you're suggesting though:

  • If your "Ground" object has collision, triggers, or really anything other than a mesh/mesh renderer on it, you'll probably need to keep the original game object you instantiated around with the mesh renderer disabled/destroyed.
  • [I may be wrong on this, but] Unity doesn't know when exactly it's safe to delete a mesh. Make sure you're not leaking meshes after creating them with CombineMeshes.
  • A single mesh in unity cannot have more than 65000 verts. If you're trying to combine an entire level made up of relatively small, detailed tiles, this might be an issue. You'll have to check manually to make sure your vert count is below that, and if it isn't generate multiple meshes.
  • If you can, make as many of your tiles use the same material as possible (i.e. atlas everything you can), so make it so that you have as few meshes as possible. CombineMeshes will make each mesh it's own submesh, but I don't know how efficient that is at combining draws of submeshes with the same material.