0 votes

I'm trying to set up a program where it loads the player's position at the start of the level but when I try to get the data from the dictionary I saved it in I get this error.

invalid get index 'player_x' (on base: 'dictionary')

I've been loosely following this tutorial (https://www.youtube.com/watch?v=mV86a8TWSc4) and my code seems to match up however I have made significant changes to suit my program.
how do I fix this?

relevant code:

code for scene:

    extends Node2D

onready var player = $player

onready var game_data = SaveFiles.game_data

func _ready():
    SaveFiles.load_data()
    SaveFiles.save_data()
    if SaveFiles.enter == true:
        player.position.x = game_data.player_x
        SaveFiles.enter = false
    else:
        player.position = Vector2 (970,300)

code in autoload:

func load_data():
    var file = File.new()
    if not file.file_exists(current):
        game_data = {
            "player_name": "farmer",
            "player_x": 100,
            "player_y": 100,
        }
        save_data()
    file.open(current, File.READ)
    game_data = file.get_var()
    file.close()
Godot version 3.44
in Engine by (21 points)

1 Answer

+1 vote

it looks very unstable
how do You know what is resolved first - onready var or ready() function ?
I am pretty sure dictionary is not loaded at a time your ready function requests its entry.
Above everything else You run save data at the same time ?

You need to make it simpler, so it is resolved one line after the other.
Make load_data return game_data and request it in ready :

func _ready():
        if file exists :
               var data = load_data()
               player.position.x = data.player.x
by (7,447 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.