0 votes

This code does not work for me to save an array, what am I doing wrong?

func _ready():
    load_score()

func _physics_process(delta):

    if Input.is_action_just_pressed("ui_accept"):
        print(array[0])
        print(array[1])
        array[0] += 1
        array[1] += 1
        save_score()

func save_score():
    var file = File.new()
    file.open(score_file, File.WRITE)
    file.store_var(array[0])
    file.close()

func load_score():
    var file = File.new()
    file.open(score_file, File.READ)
    array = file.get_as_text()
    file.close()
in Projects by (134 points)

2 Answers

0 votes

Here's some basic persistence code that can save and load a dictionary (as JSON)...

onready var persistFile = "user://savedata.txt"
onready var saveHandle = File.new()
var saveDict

func _ready():
    saveDict = {
        SCORE: 0,
        COIN_COUNT: 0,
        SOUNDFX_ISMUTED: false,
        MUSIC_ISMUTED: false
    }

func saveUserData():
    saveHandle.open(persistFile, File.WRITE)
    saveHandle.store_line(to_json(saveDict))
    saveHandle.close()

func loadUserData():
    # If we don't yet have a save file to load, create a default one...
    if !saveHandle.file_exists(persistFile):
        saveUserData()

    saveHandle.open(persistFile, File.READ)
    saveDict = parse_json(saveHandle.get_line())
    saveHandle.close()
by (10,750 points)
edited by
0 votes

Let's look at a small example:

In [819]: N
Out[819]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])

In [820]: data={'N':N}

In [821]: np.save('temp.npy',data)

In [822]: data2=np.load('temp.npy')

In [823]: data2
Out[823]: 
array({'N': array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])}, dtype=object)

np.save is designed to save numpy arrays. data is a dictionary. So it wrapped it in a object array, and used pickle to save that object. Your data2 probably has the same character.

You get at the array with:

In [826]: data2[()]['N']
Out[826]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])
by (22 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 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 webmaster@godotengine.org with your username.

Categories