godot-start/script/demo14_file/file.gd

54 lines
1.1 KiB
GDScript
Raw Normal View History

2021-10-07 07:39:57 +00:00
extends Node2D
const TimeUtils = preload("res://zfoo/scheduler/TimeUtils.gd")
const FileUtils = preload("res://zfoo/util/FileUtils.gd")
# Dictionary
var content = "hello file!!!"
# path string
var filePath: String = "user://playerData.txt"
func _ready() -> void:
print("Original Data: ", content)
self.loadData()
print("Altered Data: ", content)
func saveData() -> void:
2021-10-07 10:38:10 +00:00
var saveFile = File.new()
saveFile.open(filePath, File.WRITE)
print(saveFile.get_path_absolute())
2021-10-07 07:39:57 +00:00
2021-10-07 10:38:10 +00:00
# bread and butter
saveFile.store_line(content)
saveFile.close()
2021-10-07 07:39:57 +00:00
2021-10-07 10:38:10 +00:00
#FileUtils.writeStringToFile(filePath, content)
2021-10-07 07:39:57 +00:00
func loadData() -> void:
2021-10-07 10:38:10 +00:00
var dataFile = File.new()
# make sure our file exists on users system
if not dataFile.file_exists(filePath):
return # File does not exist
# allow reading only for file
dataFile.open(filePath, File.READ)
content = dataFile.get_as_text()
dataFile.close()
#content = FileUtils.readFileToString(filePath)
2021-10-07 07:39:57 +00:00
2021-10-07 10:38:10 +00:00
# 退出的时候回调
2021-10-07 07:39:57 +00:00
func _notification(what):
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
content = content + TimeUtils.currentTimeMillis() as String
self.saveData()
get_tree().quit() # quitting the game