How to optimize spawning thousands of objects

Godot Version

v4.2.2.stable.official [15073afe3]

Question

Code Here (PasteBin)

Hi, I’m trying to make a chunk loader system for a 3d tile game. I’ve done some testing and it looks like instantiating the StaticTile scene causes lag when done so many times.

I cannot simply spawn a StaticBody in code because I need more flexibility, This is just starting. Is there anything I can do to optimize this? E.G Is there a way to re-use the same instantiated scene so I don’t have to re-load it a bunch

You can post the code here with a code block.

Example:

```
Code
```

Output:

Code 
Your code:
func _load_chunk(pos: Vector3) -> void:
    pos *= 25
 
    print("Trying to load at" + str(pos))
    print(!LoadedChunks.has(pos))
 
    if !LoadedChunks.has(pos):
        print("Loading Chunk at" + str(pos))
        var NewChunk = ChunkInst.instantiate()
 
        NewChunk.position = pos
        NewChunk.name = Globals.vector3_to_str(pos)
        LoadedChunks.append(pos)
 
        var all_vectors = Globals.get_vector3_square(25, 25)
 
        var StaticTile: PackedScene = preload("res://Assets/Enviroment/TilingSystem/TileFabs/StaticTile.tscn")
        for vector in all_vectors:
            # pass
            var NewTile = StaticTile.instantiate()
            print(NewTile)
            NewTile.position = vector
 
            NewChunk.add_child(NewTile)
 
        ChunkCont.call_deferred("add_child", NewChunk)
        # _debug_add(ChunkCont, NewChunk)
1 Like

Have you tried using a TileMapPattern?

I can’t do that because in the future I’m going to need more than just meshes,

Tiles can be scenes

Alright I’ll look at that but are there ways to spawn things like that regardless?

As far as your approach goes that is probably the best way to do it.

If you are experiencing load lag you can make the chunks smaller. You can use a separate thread to load them, you can create a pool of objects that can be reused.

If you use the pattern approach you are just setting integers and coordinates then letting the tilemap class setup the chunk for you in c++ native realm.

1 Like

It’s already on a separate thread, What do you mean by pool? How would I make one

A pool, or resource pool, is sometimes an array of objects references that are initialized but never freed. They are used and, when done, put back. This saves time when you never have to allocating them in memory or free them. This could even apply for threads.

Also If this is truly a 3d tile system do you use a multimesh for the tile types?