In Reference class - The method "get_tree()" isn't declared in the current class error in Godot

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

I am currently working on my game’s save and load states, and I created a global script to use it. The script extends Reference class and uses the .dat file extension for saving and loading files. But I can’t use the method get_tree() in the script.
I get the error: The method get_tree() isn't declared in the current class.

I think the problem is that Reference is not connected to the SceneTree. So I tried using a player instance and use get_tree() on that like this:

const PLAYER_CHARACTER = preload("res://Player/Player.tscn")

var player = PLAYER_CHARACTER.instance()

player.get_tree().change_scene("res://Map/" + player_data.scene)

But then I get this error: Attempt to call function 'change_scene' in base 'null_instance' on a null instance.

I am a little confused on how to change the scene from this script when I load a save file. I need this to complete my save and load states.
The code is here:


extends Reference

get_tree().change_scene("res://Map/" + player_data.scene)

I appreciate any kind of explanation on why this is the case and any godot docs that can help me better understand this issue.

:bust_in_silhouette: Reply From: Wakatta

Two reasons

Like you’ve said Reference is not part of the scenetree and cannot be added to it so naturally it cannot directly access it

get_tree() is a method belonging to Nodes

Cause of null_instance error

The player var is not yet “ready”

  • which happens when its _ready() function / notification is called
  • which happens when it is added to the scenetree

Possible Solutions

Make your save class an Autoload Node

extends Node

func load_map():
    get_tree().change_scene("res://Map/" + player_data.scene)

Or reference your class every time you want to use it

#Save class
class_name GameData
extends Reference

func _save():
    pass

func load_all():
    pass

.

#Level Scene

func _ready():
    var data = GameData.new()
    var player_data = data.load_all()
    get_tree().change_scene("res://Map/" + player_data.scene)