Godot Engine key-value based database

2018 04 22 2 Comments

Here are you simple database for Godot Engine. I got inspired from this answer at godotengine qa.

func SetValue(key, value):
	var data = {key: value}
	var file = File.new()
	if file.open("user://shared_pref.sav", File.WRITE) != 0:
	    print("Error opening file")
	# Save the dictionary as JSON (or whatever you want, JSON is convenient here because it's built-in)

func GetValue(key):
	var file = File.new()
	if not file.file_exists("user://shared_pref.sav"):
	    print("No file saved!")
	# Open existing file
	if file.open("user://shared_pref.sav", File.READ) != 0:
	    print("Error opening file")
	# Get the data
	var data = {}
	data = parse_json(file.get_line())
	if data.has(key):
		return data[key]
		print(key, " [key] not assigned in saved_data")
		return 0

Save above file named Database.gd … To use it import like this:

onready var Database = preload("res://Database.gd").new()

Here you are ready to save values to database:

Database.SetValue("SomeValue", "test")
var foo = Database.GetValue("SomeValue")


2 responses to “Godot Engine key-value based database”

  1. morgash says:

    I have found your page by searching a confirmation over dictionnaries in godot.

    I have not tested your script directly but the File.WRITE mode erase old data. So you save only one info in your file, you should use File.READ_WRITE to not erase it each time.

    Otherwise, it’s good 😀

Leave a Reply

Your email address will not be published. Required fields are marked *