Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to batch a hundred cubes of different colours?

Discussion in 'General Graphics' started by TheGaul, May 16, 2019.

  1. TheGaul

    TheGaul

    Joined:
    Apr 15, 2019
    Posts:
    199
    Say I want to just put a hundred cubes on the screen of the same size. Hopefully if they all have the same material they will all batch together.

    But if I wanted them all random colours, is there a way for them to still batch?

    I mean I can think of one way in which the shader has a color dependent on world position. But I think that's not ideal.

    Is there a trick like how particles are batched with different colours? i.e. somehow they all have the same material but different colours?

    (For example I might want to procedurally render some stars but have the stars different colours).
    (This isn't a Minecraft question!)
     
    Last edited: May 16, 2019
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,616
    You could make a single texture that has a swatch of each color, then change the UVs on each cube to be within one of the swatches.
     
  3. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Once batched, the “cubes” don’t know where they are. It’s just one big mesh with a pivot at 0,0,0. You could do random colors per vertex, or per pixel world position, but then there’s no guarantee each “cube” is a single color.

    Vertex colors. Particle systems generate a single large mesh with vertex colors assigned, as well as potentially other arbitrary data stored in the UV channels, like size, or position, or another color or two.

    @kdgalla ‘s answer is an option too, but really it’s the same solution in terms of it being “store more information in the vertex data”. Could be another UV set, could be a color, could be a seed to drive some pseudo random function.

    If you want to use a single mesh and modify the colors, you could make copies of the mesh and add vertex colors to each copy, but you’re better off using AdditionalVertexStreams which lets you add vertex data to existing meshes without having to make copies of the entire mesh. You could also of course just use a single mesh with all of the stars already added with pre-assigned vertex colors.


    The other option is don’t use batching, Use instancing and make a simple shader with an instanced _Color property. Then use material property blocks to set the color on each renderer. Or use DrawMeshInstanced to draw the “cubes” manually with out having all of the extra game objects and components in the scene.