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 changescene(scenename):
deffercall("defferedchangescene", scene_name)
func defferedchangescene(scenename):
var path = SCENEPATH + scenename + ".tscn"
var root = gettree().getroot()
var current = root.getchild(root.getchildcount() - 1)
current.free()
var sceneresource = ResourceLoader.load(path)
var newscene = sceneresource.instance()
gettree().getroot().addchild(newscene)
gettree().setcurrentscene(newscene)
func process(delta):
if Input.isactionpressed("close"):
get_tree().quit()
func deffercall(funcname, funcparam):
calldeferred(funcname, funcparam)
--[Shortened scripts:]--
menu.gd
extends Node
func ready():
var scenename = gettree().getcurrentscene().getname()
print(scene_name) # returns 'menu'
on full version of the script, mechanism that called changescene here
func changescene():
levelManager.change_scene("game")
game.gd
extends Node
game variables declared here
func ready():
var scenename = gettree().getcurrentscene().getname()
print(scenename) #returns an error due to gettree().getcurrentscene() 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 currentscenename
--
menu.gd and
game.gd --
var scenename = self.getname()
levelManager.currentscenename(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.