跟着Hi小胡的这个小教程自己做了一遍,Godot的文件存取,还是跟VB6非常相似的。
之所以跟着做这个实例,是因为自己对Godot的文件存取还是相当不熟悉的。这算是个敲门砖。另外,顺道可以学点儿控件的使用,何乐而不为。
https://www.bilibili.com/video/BV1xK411s7gf?from=search&seid=10638041312261711716

我在他的教程基础上,使用了容器控件来形成自适应布局。
最终效果:
image.png
image.png
image.png

场景构成

image.png

代码

  1. extends Control
  2. var current_fPath = "" # 当前打开文件的路径
  3. func _ready():
  4. $VBoxContainer/HBoxContainer/fileMenu.get_popup().connect("id_pressed",self,"fileMenu_Pressed")
  5. pass
  6. # 文件下拉菜单点击
  7. func fileMenu_Pressed(id):
  8. if id == 0: # 打开
  9. $openDialog.popup()
  10. pass
  11. elif id == 1: # 保存
  12. if current_fPath != "": # 存在打开的文件
  13. saveFile(current_fPath,$VBoxContainer/txt1.text)
  14. $VBoxContainer/status.text = "文件" + current_fPath + "已保存"
  15. else:
  16. $saveDialog.popup()
  17. pass
  18. elif id == 3: # 新建
  19. if current_fPath != "": # 有文件正在编辑
  20. $newConfirm.popup()
  21. else:
  22. $VBoxContainer/txt1.text = "" # 清空文本编辑器内容
  23. pass
  24. elif id == 5: # 退出
  25. get_tree().quit()
  26. pass
  27. pass
  28. # ======================= 信号处理 ============================
  29. # 打开文件对话框
  30. func _on_openDialog_file_selected(path):
  31. current_fPath = path # 保存打开的文件路径
  32. $VBoxContainer/txt1.text = loadFileString(path) # 加载文件内容到文本编辑器
  33. $VBoxContainer/status.text = "已打开文件:" + current_fPath # 更新状态栏信息
  34. # 保存文件对话框
  35. func _on_saveDialog_file_selected(path):
  36. current_fPath = path # 保存打开的文件路径
  37. saveFile(path,$VBoxContainer/txt1.text) # 保存文本编辑器内容到指定路径的文件
  38. $VBoxContainer/status.text = "文件" + path + "已保存" # 更新状态栏信息
  39. # 确认关闭当前文件并新建
  40. func _on_newConfirm_confirmed():
  41. saveFile(current_fPath,$VBoxContainer/txt1.text) # 保存正在编辑的文件
  42. current_fPath = "" # 清空当前打开文件的路径
  43. $VBoxContainer/txt1.text = "" # 清空文本编辑器内容
  44. # ======================= 自定义函数 ============================
  45. # 保存字符串到指定路径的文件
  46. func saveFile(path:String,content:String):
  47. var file = File.new()
  48. file.open(path,File.WRITE)
  49. file.store_string(content)
  50. file.close()
  51. # 返回指令路径文件中的内容
  52. func loadFileString(path:String):
  53. var file = File.new()
  54. file.open(path,File.READ)
  55. var string = file.get_as_text()
  56. file.close()
  57. return string