2
\$\begingroup\$

I'm trying to save my game on Godot Engine by pressing a "save" button but I get this message error when i do:

Attempt to call function 'get_nodes_in_group' in base 'null instance' on a null instance

this is my project code:

#File.gd, contains the methods to write and read over the file
extends Node

var path_name := "res://resource/debug/save"
var file := "sav.tres"


class_name WriterReader

func write():
    var writer := Save.new()
    var directory := Directory.new()

    writer.version = ProjectSettings.get_setting("application/config/Version")
    for node in get_tree().get_nodes_in_group("persistance"): #it's  the line that thows the error
        node.save(writer)
    print(writer.version)

    if not directory.dir_exists(path_name):
        directory.make_dir_recursive(path_name)

    if ResourceSaver.save(path_name.plus_file(file), writer) != OK:
        print("ERROR")


#the save button gdscript file
extends Button


func _ready():
    var save = Save.new()
    self.connect("pressed", self, "save_game", [save])


func save_game(save):
    var s = WriterReader.new()
    s.write()



#it's the part of code where of the player character is saving 
extends KinematicBody2D
...

func save(write: Resource):
    write.dat = {"position": position, "health": health}

#sav.gd, singleton used to save the player data

extends Resource

class_name Save

var dat : Dictionary = {}
var version := ""

I'm a beginner on Godot so I cannot figure out why this happens.

could somebody explain me, please?

Thanks

\$\endgroup\$
  • \$\begingroup\$ Sorry about the misspelling but yes, i checked my group and contains all the nodes i want to save \$\endgroup\$ – EmmanCanVaz_95 Dec 6 '19 at 4:08
5
\$\begingroup\$

Your WriterReader is calling get_tree while it is not part of the SceneTree. You could do something like this:

func save_game(save):
    var s = WriterReader.new()
    add_child(s)
    s.write()

Since it looks like your WriterReader isn't designed to be part of the scene tree, it might make more sense to pass the objects into write from outside:

# in WriterReader.gd:
static func write(nodes: Array):
    # ...
    for node in nodes:
        node.save(writer)
    # ...

# in Button.gd:
func save_game(save):
    # this should work, as your Button is part of the SceneTree
    WriterReader.write(get_tree().get_nodes_in_group("persistance"))

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Grettings Thank you for answering :D it was so useful and now the save system works well! Thank you so much! \$\endgroup\$ – EmmanCanVaz_95 Dec 6 '19 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.