I'm trying to use yield
to go from this code:
func change_level(toLevel: String):
level.save_player()
if level.player != null:
level.remove_child(level.player)
level.save_state()
var _succ = get_tree().change_scene("res://Scenes/Levels/"
+ toLevel + "/" + toLevel + ".tscn")
yield(get_tree().create_timer(0.1), "timeout")
level.load_state()
func move_player(toLevel: String, toSpawn: String):
level.save_player()
if level.player != null:
level.remove_child(level.player)
level.save_state()
var _succ = get_tree().change_scene("res://Scenes/Levels/"
+ toLevel + "/" + toLevel + ".tscn")
yield(get_tree().create_timer(0.1), "timeout")
level.load_state()
level.load_player()
level.move_player_to(toSpawn)
to this code:
func change_level(toLevel: String):
level.save_player()
if level.player != null:
level.remove_child(level.player)
level.save_state()
var _succ = get_tree().change_scene("res://Scenes/Levels/"
+ toLevel + "/" + toLevel + ".tscn")
yield(get_tree().create_timer(0.1), "timeout")
level.load_state()
signal levelLoaded
func move_player(toLevel: String, toSpawn: String):
yield(change_level(toLevel), 'levelLoaded')
level.load_player()
level.move_player_to(toSpawn)
First code works fine, the second one throws an error
Error connecting to signal: levelLoaded during yield
at yield(change_level(toLevel), 'levelLoaded')
in function move_player
I tried the second code without the yield(change_level(toLevel), 'levelLoaded')
. Instead I put just change_level(toLevel)
After some debugging of this version of the code here's what I noticed is happening:
-I call move_player
-change_level
is called
-change_level
returns on yield(get_tree().create_timer(5), "timeout")
without executing level.load_state()
-move_player
continues with level.load_player()
-level.load_player()
causes other errors
This is why it crossed my mind to put change_level
in yield
in move_player
function, but as you can see, it returns the error described above.
Is it possible to not have so much duplicated code for both functions and use yield to help me?
I know I can use timers but that just makes a mess out of the whole code. I'd like my code to be clean.
Also, the reason I have yield(get_tree().create_timer(0.1), "timeout")
in change_level
function is because this code is in preloaded script called LevelHelper
.
This script has var level: Level
and that's what I'm using to allow objects in level to spawn other objects.
When Level._ready()
is called, it is doing this LevelHelper.level = self
.
Because I'm changing scenes in the singleton script LevelHelper
via var _succ = get_tree().change_scene("res://Scenes/Levels/" + toLevel + "/" + toLevel + ".tscn")
in function LevelHelper.change_level
, I need to wait for the Level._ready()
to be called so the LevelHelper.level
is refreshed and I can then use the same variable (LevelHelper.level
) to load level's last state, load player and so on.