Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | jagc |
I was trying to get the name of the current scene by using get_tree().get_current_scene().get_name()
but i’m getting the error:
Attempt to call function ‘get_name’ in base ‘null instance’ on a null
instance.
I found out that get_current_scene()
was giving me null
. This is after a change scene where the function was working as intended.
i.e.
get_tree().get_current_scene().get_name()
in menu.gd returns menu
get_tree().get_current_scene().get_name()
in game.gd returns the error because get_tree().get_current_scene()
is null
levelManager.gd (autoloaded singleton) [full script]
extends Node const SCENE_PATH = "res://scenes/" func change_scene(scene_name): deffer_call("_deffered_change_scene", scene_name) func _deffered_change_scene(scene_name): var path = SCENE_PATH + scene_name + ".tscn" var root = get_tree().get_root() var current = root.get_child(root.get_child_count() - 1) current.free() var scene_resource = ResourceLoader.load(path) var new_scene = scene_resource.instance() get_tree().get_root().add_child(new_scene) get_tree().set_current_scene(new_scene) func _process(_delta): if Input.is_action_pressed("close"): get_tree().quit() func deffer_call(func_name, func_param): call_deferred(func_name, func_param)
–[Shortened scripts:]–
menu.gd
extends Node func _ready(): var scene_name = get_tree().get_current_scene().get_name() print(scene_name) # returns 'menu' # on full version of the script, mechanism that called _change_scene here func _change_scene(): levelManager.change_scene("game")
game.gd
extends Node #game variables declared here func _ready(): var scene_name = get_tree().get_current_scene().get_name() print(scene_name) #returns an error due to get_tree().get_current_scene() being null # rest of the game logic code here
I want to know why this is the case. Is there something wrong with the way i changed scenes from levelManager.gd?
I resolved this issue by:
setting var current_scene_name
in levelManager.gd
– both in menu.gd and game.gd –
re-setting current_scene_name
by calling self.get_name()
i.e.
levelManager.gd
var current_scene_name
–menu.gd and game.gd –
var scene_name = self.get_name() levelManager.current_scene_name(scene_name)
^ This is obviously a workaround. It works but i still want to know why i’m getting different outputs after calling get_tree()
while they practically are in the same remote location in the node.
link to screenshot because embedding images doesn’t seem to work:
treeScreenshotBeforeAndAfterChangingScenes
This is probably a duplicate of this but this isn’t exactly an answer and i’m not entirely sure it can be a comment there either.
Just BTW. This is much easier to do with get_tree().get_current_scene().get_filename()
. This returns the path in the filesystem to the current scene.
scrubswithnosleeves | 2021-04-09 18:56