You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot4首次加载PlayerData资源为空,调用duplicate报错求助

Godot4中使用Resource实现存档时首次加载空引用问题修复

问题描述

在Godot4中尝试用Resource实现玩家变量的保存与加载时,遇到以下问题:首次启动未执行保存操作时,加载资源返回空引用,调用duplicate方法报错;但执行一次保存后功能恢复正常。

相关代码

playerData.gd

extends Resource

class_name PlayerData

@export var health = 10

func change_health(value: int):
    health+=value

Main.gd

extends Control

var save_file_path = "user://save/"
var save_file_name = "PlayerData.tres"

var playerData = PlayerData.new()


# Called when the node enters the scene tree for the first time.
func _ready():
    verify_save_dir(save_file_path)
    
    playerData = ResourceLoader.load(save_file_path+save_file_name).duplicate(true) # 首次加载返回null
    
    if playerData:
        print(playerData.health)


func save_player_data():
    ResourceSaver.save(playerData, save_file_path + save_file_name)

func verify_save_dir(path : String):
    DirAccess.make_dir_absolute(path)
    
func _on_button_pressed():
    playerData.change_health(20)
    
    if playerData:
        print(playerData.health)
    

func _on_save_button_score_pressed():
    save_player_data() 

错误信息

Cannot call method 'duplicate' on a null value.

问题原因及修复方案

问题根源

首次启动游戏时,user://save/PlayerData.tres文件尚未创建,ResourceLoader.load会返回null,此时直接调用null.duplicate()必然触发报错。

修复步骤

修改_ready函数,先判断加载结果是否有效,若为空则使用新创建的PlayerData实例,而非强行调用duplicate:

func _ready():
    verify_save_dir(save_file_path)
    
    # 先尝试加载存档文件
    var loaded_data = ResourceLoader.load(save_file_path+save_file_name)
    # 加载成功则复制实例,失败则使用新实例
    playerData = loaded_data.duplicate(true) if loaded_data else PlayerData.new()
    
    print(playerData.health)

额外说明

  • 这样修改后,首次启动会使用默认值初始化玩家数据,执行保存操作后,后续启动就能加载到之前保存的内容。
  • 保留duplicate是为了避免直接修改加载的资源实例(Godot中加载的资源默认是共享的),复制实例可以确保操作的是独立数据。

内容的提问来源于stack exchange,提问作者Rifat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:42:23