I am attempting to create a data sore script in which to save just three leaderstats. Everything seems to be working fine except when it gets to line 22, where the script crashes. I know I am bad at errors, which I am still learning thoroughly, but can anyone explain to me why this problem occurred?
This is the error:
Workspace.PlayerEntered:22: attempt to index local ‘savedValues’ (a number value)
local DataStore = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerAdded:connect(function(player) local stats = Instance.new("IntValue", player) stats.Name = "leaderstats" local win = Instance.new("IntValue", stats) win.Name = "Wins" local kill = Instance.new("IntValue", stats) kill.Name = "Kills" local death = Instance.new("IntValue", stats) death.Name = "Deaths" local key = "player-"..player.UserId local savedValues = DataStore:GetAsync(key) if savedValues then win.Value = savedValues[1] kill.Value = savedValues[2] death.Value = savedValues[3] else local winToSave = (win.Value) local killToSave = (kill.Value) local deathToSave = (death.Value) DataStore:SetAsync(key, winToSave) DataStore:SetAsync(key, killToSave) DataStore:SetAsync(key, deathToSave) end end)
This code is the save.
local DataStore = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerRemoving:connect(function(player) local short = player.leaderstats local key = "player-"..player.UserId local winToSave = (short.Wins.Value) local killToSave = (short.Kills.Value) local deathToSave = (short.Deaths.Value) DataStore:SetAsync(key, winToSave) DataStore:SetAsync(key, killToSave) DataStore:SetAsync(key, deathToSave) end)
After line 25 of the first script, you save the values very weird. I would suggest making a table and saving the table to the DataStore, as this would probably fix your problem,
local DataStore = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerAdded:connect(function(player) local stats = Instance.new("IntValue", player) stats.Name = "leaderstats" local win = Instance.new("IntValue", stats) win.Name = "Wins" local kill = Instance.new("IntValue", stats) kill.Name = "Kills" local death = Instance.new("IntValue", stats) death.Name = "Deaths" local key = "player-"..player.UserId local savedValues = DataStore:GetAsync(key) if savedValues then win.Value = savedValues[1] kill.Value = savedValues[2] death.Value = savedValues[3] else local SaveValues = { win.Value; kill.Value; death.Value } DataStore:SetAsync(key, SaveValues) end end)
Now you should do the same for the second script,
local DataStore = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerRemoving:connect(function(player) local short = player.leaderstats local key = "player-"..player.UserId local SaveValues = { player.leaderstats.win.Value; player.leaderstats.kill.Value; player.leaderstats.death.Value } DataStore:SetAsync(key, SaveValues) end)
I hope this works and helps.
Good Luck!