Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why am i getting a nil error for "Cash" in this Data Store script?

Asked by 3 years ago
local DataStoreService = game:GetService("DataStoreService")
  local myDataStore = DataStoreService:GetDataStore("myDataStore")
  
  game.Players.PlayerAdded:Connect(function(player)
  
  local leaderstats = Instance.new("Folder")
  leaderstats.Name = "leaderstats"
  leaderstats.Parent = player
  
  local Cash = Instance.new("IntValue")
  Cash.Name = "Cash"
  Cash.Parent = leaderstats
  
  local Wins = Instance.new("IntValue")
  Wins.Name = "Wins"
  Wins.Parent = leaderstats
  
  local playerUserId = "Player_"..player.UserId
  
  --Load Data
  
  local data
  local success, errormessage = pcall(function()
  data = myDataStore:GetAsync(playerUserId)
  
  end)
  if success then 
  Cash.Value = data.Cash
  Wins.Value = data.Wins
  
          end
  end)
  
  game.Players.PlayerRemoving:Connect(function(player)
  local playerUserId = "player_"..player.UserId
  
  local data = {
  Cash = player.leaderstats.Cash.Value;
  Wins = player.leaderstats.Wins.Value;
  }
  
  local success, errormessage = pcall(function()
  myDataStore:SetAsync(playerUserId, data)
  end)
  if success then 
  print("works")
  else
  print("none")
  warn(errormessage)
  end
  end)
  

when i try to save, the output gives this error - ServerScriptService.Save:28: attempt to index nil with 'Cash' Im not sure how to fix it, any help would be great.

1
Key's are unique identifiers, any minor difference, even capitalization, can make them worlds apart. On line 18, you declare a Key with a capital 'P' in 'Player', whereas the Key you save to is 'player'. There is no data allocated under that key, therefore you recieve nil. Ziffixture 6913 — 3y

Answer this question