【问题标题】:Godot save select screenGodot保存选择屏幕
【发布时间】:2021-05-23 08:39:47
【问题描述】:

创建具有多个可选保存文件的保存选择屏幕的最佳方法是什么,到目前为止,我已经设法使一个保存文件正常工作,但我不知道如何管理多个文件,保存到它并在需要时加载那个特定的

这是我的保存和加载系统的代码

const FILE_NAME = "user://game-data1.json"

var player = {
    "collected_level_one":false,
    
}

func save():
    var file = File.new()
    file.open(FILE_NAME, File.WRITE)
    file.store_string(to_json(player))
    file.close()

func load():
    var file = File.new()
    if file.file_exists(FILE_NAME):
        file.open(FILE_NAME, File.READ)
        var data = parse_json(file.get_as_text())
        file.close()
        if typeof(data) == TYPE_DICTIONARY:
            player = data
        else:
            printerr("Corrupted data!")
    else:
        printerr("No saved data!")

    

【问题讨论】:

    标签: save godot gdscript


    【解决方案1】:

    如果你想拥有多个存档文件。您将需要使用多个可选插槽和一个保存和加载按钮。获取您选择的项目,然后在单击它们时保存或加载。

    调用保存或加载:

    # Clicked save button.
    func _on_Button_pressed_save() -> void:
        # Get the selected save/load slot.
        var index
        # Save into the selected file.
        SaveSystem.save(index)
    
    # Clicked load button.
    func _on_Button_pressed_save() -> void:
        # Get the selected save/load slot.
        var index
        # Load the selected file.
        SaveSystem.load(index)
    

    您还需要将 Savesystem 脚本添加为 Singleton (Autoload)。以便您可以在其他脚本中轻松访问它。


    添加对函数的调用后,您需要相应地更改它们以便能够管理多个保存文件。

    管理多个保存文件:

    # Clicked save button.
    const FILE_NAME = "user://game-data"
    const FILE_EXTENSION = ".json"
    
    var player = {
        "collected_level_one":false,
    }
    
    # Saves into the file with the given index.
    func save(index : int) -> void:
        var file := File.new()
        var file_name := FILE_NAME + to_str(index) + FILE_EXTENSION
        file.open(file_name, File.WRITE)
        file.store_string(to_json(player))
        file.close()
    
    # Loads the file with the given index.
    func load(index : int) -> void:
        var file := File.new()
        var file_name := FILE_NAME + to_str(index) + FILE_EXTENSION
        if file.file_exists(file_name):
            file.open(FILE_NAME, File.READ)
            var data := parse_json(file.get_as_text())
            file.close()
            if typeof(data) == TYPE_DICTIONARY:
                player = data
            else:
                printerr("Corrupted data!")
        else:
            printerr("No saved data!")
    

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多