Optimization using MultiMeshes

    When the amount of objects reach the hundreds of thousands or millions, none of these approaches are efficient anymore. Still, depending on the requirements, there is one more optimization possible.

    A is a single draw primitive that can draw up to millions of objects in one go. It’s extremely efficient because it uses the GPU hardware to do this (in OpenGL ES 2.0, it’s less efficient because there is no hardware support for it, though).

    If the objects are simple enough (just a couple of vertices), this is generally not much of a problem as most modern GPUs are optimized for this use case. A workaround is to create several MultiMeshes for different areas of the world.

    It is also possible to execute some logic inside the vertex shader (using the or INSTANCE_CUSTOM built-in constants). For an example of animating thousands of objects in a MultiMesh, see the Animating thousands of fish tutorial. Information to the shader can be provided via textures (there are floating-point formats which are ideal for this).

    Finally, it’s not required to have all MultiMesh instances visible. The amount of visible ones can be controlled with the MultiMesh.visible_instance_count property. The typical workflow is to allocate the maximum amount of instances that will be used, then change the amount visible depending on how many are currently needed.

    Multimesh example

    Here is an example of using a MultiMesh from code. Languages other than GDScript may be more efficient for millions of objects, but for a few thousands, GDScript should be fine.

    C#

    1. using System;
    2. public class YourClassName : MultiMeshInstance
    3. {
    4. public override void _Ready()
    5. {
    6. Multimesh = new MultiMesh();
    7. // Set the format first.
    8. Multimesh.TransformFormat = MultiMesh.TransformFormatEnum.Transform3d;
    9. Multimesh.ColorFormat = MultiMesh.ColorFormatEnum.None;
    10. Multimesh.CustomDataFormat = MultiMesh.CustomDataFormatEnum.None;
    11. // Then resize (otherwise, changing the format is not allowed)
    12. Multimesh.InstanceCount = 1000;
    13. // Set the transform of the instances.
    14. for (int i = 0; i < Multimesh.VisibleInstanceCount; i++)
    15. {
    16. Multimesh.SetInstanceTransform(i, new Transform(Basis.Identity, new Vector3(i * 20, 0, 0)));
    17. }
    18. }