Roblox Data Store V2读取返回nil 触发Attempt to index nil with Version报错求助
核心错误原因
LoadPlayerData函数中,pcall包裹的匿名函数没有返回GetAsync的执行结果,导致调用成功后CurrentNumber、KeyInfo两个变量始终为nil,触发索引空值的报错。- 测试触发逻辑顺序错误:玩家进入游戏时先触发
PlayerAdded加载数据,此时还未执行过仅在退游时触发的SaveNumberData逻辑,首次读取必然无数据。 - 可选优化:当前写死了
PlayerKey = 'Player_1234',所有玩家会共享同一个存储键,正式使用可替换为'Player_'..Player.UserId区分不同玩家数据。
修正代码
仅需要修改 LoadPlayerData 中 pcall 的包裹逻辑即可,完整修正后的代码如下:
local DataStoreService = game:GetService('DataStoreService') local Players = game:GetService('Players') -- Data Stores: -- 启用Data Stores V2 local Options = Instance.new('DataStoreOptions') Options:SetExperimentalFeatures({["v2"] = true}) local NumberStore:DataStore = DataStoreService:GetDataStore("PlayerNumber", "global", Options) local SetOptions = Instance.new('DataStoreSetOptions') SetOptions:SetMetadata({['PlayerNumberType'] = 'Int'}) local function SaveNumberData(Player:Player) local Number = 1 local PlayerKey = 'Player_1234' -- 正式使用可改为 'Player_'..Player.UserId local Success, Errormessage = pcall(function() NumberStore:SetAsync(PlayerKey, Number, {Player.UserId}, SetOptions) end) if not Success then print(Errormessage) else print('数据保存成功') end end local function LoadPlayerData(Player:Player) local PlayerKey = 'Player_1234' -- 正式使用可改为 'Player_'..Player.UserId local Success, CurrentNumber, KeyInfo:DataStoreKeyInfo = pcall(function() -- 新增return返回GetAsync的执行结果 return NumberStore:GetAsync(PlayerKey) end) if Success then print(CurrentNumber) if KeyInfo then -- 新增空判断避免首次无数据时报错 print(KeyInfo.Version) print(KeyInfo.CreatedTime) print(KeyInfo.UpdatedTime) print(KeyInfo:GetUserIds()) print(KeyInfo:GetMetadata()) end else print(CurrentNumber) end end Players.PlayerRemoving:Connect(SaveNumberData) Players.PlayerAdded:Connect(LoadPlayerData)
测试方法
第一次进入游戏退出后会触发保存,第二次进入游戏即可读取到已存储的数据。也可以在服务器逻辑中新增主动触发保存的测试逻辑,无需反复退出重进验证。
内容的提问来源于stack exchange,提问作者Arthur Buzas Baccan
相关产品推荐
相关产品推荐

