0 votes

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.

Godot version v3.5.1
in Engine by (12 points)

1 Answer

0 votes

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():

func load_all():


#Level Scene

func _ready():
    var data = GameData.new()
    var player_data = data.load_all()
    get_tree().change_scene("res://Map/" + player_data.scene)
by (6,876 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.