If conditional not working as expected

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

I have a variable called current_level which is set to the current level if I have one, and it is set to null if I don’t have one. When I change levels I first check if current_level is null or not. If it’s null I don’t do anything and if it’s not null I free it so I can load a new level. This logic some times works as expected but some times crashes unexpectedly.
I’m clearly checking if current_level != null: current_level.queue_free(). And even though current_level is NULL Godot tries to run queue_free and it crashes. Any ideas?

Where does current_level get set? It does not appear to be set at the point where you load a new level…

jgodfrey | 2020-05-21 01:20

:bust_in_silhouette: Reply From: supper_raptor

It happens because when you queue_free() a variable it does not frees instantly. In your case , you previously freed current_level and then tried to check if current_level == null but current_level was not null and tried to free it again.

To fix it ,you should assign current_level = null after calling queue_free()

func _on_game_over():
    current_level = null

func change_level():
    if current_level != null:
    #rest of the code

This is what I ended up doing yesterday, it works. Thanks for the answer

Kaan Alpar | 2020-05-21 21:41