Hi there! I'm creating a leaderboard on the player list that shows the amount of kills and wins each player has. But when I load into the game, it gives me an error: attempt to index nil value. I don't know what's wrong and all of the tutorials that I watch are outdated. Here is the code:
local DataStoreService = game:GetService("DataStoreService") local DataStore = DataStoreService:GetDataStore("FlipStats") game.Players.PlayerAdded:Connect(function(Player) local Leaderstats = Instance.new("Folder") Leaderstats.Name = "leaderstats" Leaderstats.Parent = Player local Currency = Instance.new("StringValue") Currency.Name = "Flips" Currency.Value = DataStore:GetAsync(Player.UserId).Flips or 0 Currency.Parent = Leaderstats local Currency = Instance.new("StringValue") Currency.Name = "Wins" Currency.Value = DataStore:GetAsync(Player.UserId).Wins or 0 Currency.Parent = Leaderstats end) game.Players.PlayerRemoving:Connect(function(Player) DataStore:SetAsync(Player.UserId, { ["Flips"] = Player.leaderstats.Money.Value; ["Wins"] = Player.leaderstats.Wins.Value; }) end)
The error shows up at line 10, where it says Currency.Value = DataStore:GetAsync(Player.UserId).Flips or 0
. I expect that if I got past this error, another error would show up at line 14:Currency.Value = DataStore:GetAsync(Player.UserId).Wins or 0
.
If someone could help, that would be greatly appreciated! Thanks!
Store the retrieved data in a variable, if it is nil, assign some default value to it Also you should use a pcall here to make sure that if Datastore for whatever reason is not working correctly, your code will not error Example code
local Data local success, err = pcall(function() Data = DataStore:GetAsync(Player.UserId) end) if not success then print(err) -- not necessary, but helps with debugging end if not Data then Data = { Flips = 0, Wins = 0, } end -- later on Currency.Value = Data.Flips