问题描述
我正在测试如何使用Godot 3.2.2存储游戏数据(我还测试了Godot 3.2.3-rc4)。当我在Windows上导出项目(基本上是按一个按钮,并且将1添加到得分(由标签显示))上的所有内容都运行良好时,得分已保存。但是,当我将其导出到Android手机时,数据并未保存。在导出设置中,我启用了所有权限,在手机的设置中,启用了对应用程序的存储权限。也许任何人都可以向我解释一下,并告诉我如何解决此问题,以便数据也存储在android中。
代码:
extends Node2D
var score = 0
var path = "user://save_file.json"
var save_game_data
func _ready() -> void:
load_data()
set_label_text()
func _on_Button_pressed() -> void:
score += 1
set_label_text()
func set_label_text():
$Label.text = str(score)
func _notification(what: int) -> void:
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
save_game_data = {
"score": score
}
save_data()
func save_data():
var save_game = File.new()
save_game.open(path,File.WRITE)
save_game.store_line(to_json(save_game_data))
save_game.close()
func load_data():
var save_game = File.new()
if not save_game.file_exists(path):
print("No save file found")
save_data()
return
save_game.open(path,File.READ)
save_game_data = parse_json(save_game.get_line())
score = save_game_data["score"]
print("Saved game loaded",save_game_data)
解决方法
根据the docs on NOTIFICATION_WM_QUIT_REQUEST:
在桌面平台上实施。
NOTIFICATION_WM_QUIT_REQUEST 主要是为了让您可以实现“您确定要退出吗?”对话框或类似的。移动平台一般没有这个选项——当你按下主页按钮时,窗口会关闭,不管它是否愿意。
您可以通过在分数发生变化时(或在一轮结束时等)自动保存来解决此问题。