Hello, Im OriChanRBLX, Im trying to make a PlayerData System that both saves the player inventory and player stats. But it always said 14:32:12.179 - ServerScriptService.PlayerData:39: attempt to index nil with 'Gold'. I’ve try many times and check it many times but I dont no why it still saying the error. This is my script:
local DataStoreService = game:GetService("DataStoreService")
local PlayerStats = DataStoreService:GetDataStore("PlayerData")
local SwordInvData = DataStoreService:GetDataStore("SwordInvData")
game.Players.PlayerAdded:Connect(function(plr)
local Stats = Instance.new("Folder")
Stats.Name = "Stats"
Stats.Parent = plr
local SwordInventory = Instance.new("Folder")
SwordInventory.Name = "SwordInv"
SwordInventory.Parent = plr
local Gold = Instance.new("IntValue")
Gold.Name = "Gold"
Gold.Parent = Stats
local Gems = Instance.new("IntValue")
Gems.Name = "Gems"
Gems.Parent = Stats
local Rebirth = Instance.new("IntValue")
Rebirth.Name = "Rebirth"
Rebirth.Parent = Stats
local plrUserId = "Player_".. plr.UserId
-- Load Data
local data
local success, errormessage = pcall(function()
data = PlayerStats:GetAsync(plrUserId)
end)
if success then
Gold.Value = data.Gold
Gems.Value = data.Gems
Rebirth.Value = data.Rebirth
end
local InvData
local success1, errormessage1 = pcall(function()
InvData = SwordInvData:GetAsync(plrUserId)
for i, v in pairs(InvData) do
local NewChild = Instance.new("BoolValue")
NewChild.Name = tostring(v)
NewChild.Parent = SwordInventory
end
end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
local plrUserId = "Player_".. plr.UserId
local StatsNeedToSave = {
Gold = plr.Stats.Gold.Value;
Gems = plr.Stats.Gems.Value;
Rebirth = plr.Stats.Rebirth.Value;
}
local InventoryNeedToSave = {}
local success, errormessage = pcall(function()
PlayerStats:SetAsync(plrUserId, StatsNeedToSave)
for i, v in pairs(plr.SwordInv:GetChildren()) do
table.insert(InventoryNeedToSave, i, v)
end
SwordInvData:SetAsync(plrUserId, InventoryNeedToSave)
end)
if success then
print("Player_"..plr.UserId.." data successfully saved!")
else
print("There was a error when trying to save player data")
warn(errormessage)
end
end)