跟着Hi小胡的这个小教程自己做了一遍,Godot的文件存取,还是跟VB6非常相似的。
之所以跟着做这个实例,是因为自己对Godot的文件存取还是相当不熟悉的。这算是个敲门砖。另外,顺道可以学点儿控件的使用,何乐而不为。
https://www.bilibili.com/video/BV1xK411s7gf?from=search&seid=10638041312261711716
我在他的教程基础上,使用了容器控件来形成自适应布局。
最终效果:
场景构成
代码
extends Control
var current_fPath = "" # 当前打开文件的路径
func _ready():
$VBoxContainer/HBoxContainer/fileMenu.get_popup().connect("id_pressed",self,"fileMenu_Pressed")
pass
# 文件下拉菜单点击
func fileMenu_Pressed(id):
if id == 0: # 打开
$openDialog.popup()
pass
elif id == 1: # 保存
if current_fPath != "": # 存在打开的文件
saveFile(current_fPath,$VBoxContainer/txt1.text)
$VBoxContainer/status.text = "文件" + current_fPath + "已保存"
else:
$saveDialog.popup()
pass
elif id == 3: # 新建
if current_fPath != "": # 有文件正在编辑
$newConfirm.popup()
else:
$VBoxContainer/txt1.text = "" # 清空文本编辑器内容
pass
elif id == 5: # 退出
get_tree().quit()
pass
pass
# ======================= 信号处理 ============================
# 打开文件对话框
func _on_openDialog_file_selected(path):
current_fPath = path # 保存打开的文件路径
$VBoxContainer/txt1.text = loadFileString(path) # 加载文件内容到文本编辑器
$VBoxContainer/status.text = "已打开文件:" + current_fPath # 更新状态栏信息
# 保存文件对话框
func _on_saveDialog_file_selected(path):
current_fPath = path # 保存打开的文件路径
saveFile(path,$VBoxContainer/txt1.text) # 保存文本编辑器内容到指定路径的文件
$VBoxContainer/status.text = "文件" + path + "已保存" # 更新状态栏信息
# 确认关闭当前文件并新建
func _on_newConfirm_confirmed():
saveFile(current_fPath,$VBoxContainer/txt1.text) # 保存正在编辑的文件
current_fPath = "" # 清空当前打开文件的路径
$VBoxContainer/txt1.text = "" # 清空文本编辑器内容
# ======================= 自定义函数 ============================
# 保存字符串到指定路径的文件
func saveFile(path:String,content:String):
var file = File.new()
file.open(path,File.WRITE)
file.store_string(content)
file.close()
# 返回指令路径文件中的内容
func loadFileString(path:String):
var file = File.new()
file.open(path,File.READ)
var string = file.get_as_text()
file.close()
return string