Godot Version
v4.4.1
Question
Hello everyone, I am trying to figure out how the spawn
function works in Godot. I am referring to a custom spawn function to be clear.
The doc states:
Requests a custom spawn, with data passed to spawn_function on all peers. Returns the locally spawned node instance already inside the scene tree, and added as a child of the node pointed by spawn_path.
I guess the key take-away is that it returns the locally spawned node instance
and this is clashing with the idea that I had in mind: to load resources on a different thread. The way I am approaching this, the returned Node
always seems to be null
and I am sure it has to do with the await
call.
I have it set-up along the lines of::
class_name ThreadLoader
extends Node
signal load_done
static var thread: Thread = Thread.new()
func load_threaded(resource: String) -> void:
var out: Node = load(resource).instantiate()
call_deferred("emit_signal", "load_done", out)
func _exit_tree() -> void:
thread.wait_to_finish()
In my CustomMultiplayerSpawner
I have a custom_spawn_function
which does the following:
class_name CustomMultiplayerSpawner
extends MultiplayerSpawner
var threaded_loader: ThreadLoader
func _ready() -> void:
thread_loader = ThreadLoader.new()
spawn_function = custom_spawn_function
func custom_spawn_function(resource_path: String) -> Node:
thread_loader .load_threaded(resource_path)
var node: Node = await thread_loader .load_done
return node
If I load the resource inside the custom function and return it, everything works. If I load it using another thread, it does not work. I also made sure - using breakpoints - that the node
I am returning is not null
and indeed it’s not, it loads correctly using the other thread.
So I was wondering what I am doing wrong. Is there a race condition I am not taking into consideration? Shouldn’t the method await
the load_done
signal before returning? Why is that not the case?