Why does setting tiles using threads crash the game?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mnjq2006

I have been researching on how threads work for a few days but I can’t seem to find a solution.
So I have a simple scene tree:
Node

  • TileMap

and I have a script on the TileMap node:

extends TileMap

var thread = Thread.new()

func _ready():
    thread.start(self, "generate_tiles")

func generate_tiles(data):
    for y in range(100):
	    for x in range(100):
		    set_cell(x,y,0) #btw the tileset[0] is a valid tileset I made

But why is it that when I play the project, it crashes?
When replace set_cell(x,y,0) with print(x,y), it works perfectly fine.
Is there something about threads that I should know? (Sry I’m a little new to godot threads so I don’t understand exactly how they work)

Thanks :slight_smile:

:bust_in_silhouette: Reply From: Zylann

Because anything that touches nodes that are inside the scene tree is not thread-safe. You could be setting tiles while the TileMap is ongoing processing stuff (_process, _draw…), and your calls makes it clash.

You may want to generate a 2D array in a thread (with generation logic if you do), and apply it on the main thread.
Or, maybe you could try not adding the tilemap to the scene tree and only add it when it’s done generating, but I am not sure about this one.

Oh I didn’t know about that! Thanks for the help I’ll try that out. I really appreciate it! :slight_smile:

mnjq2006 | 2020-03-24 10:44

Because anything that touches nodes that are inside the scene tree is not thread-safe.

Thanks a ton for this clarification. It should be in the docs for Thread.

blurrred | 2021-09-23 18:34