It is very poor practice to have the PlayerRemoving event handler inside of the PlayersAdded event handler because it will create a new connection for each player, and that connection will fire for any player that leaves. Your solution?
local DataStoreService = game:GetService("DataStoreService")
local Data = DataStoreService:GetDataStore("CoinsData")
game.Players.PlayerAdded:Connect(function(player)
local Coins = Instance.new("IntValue", player)
Coins.Name = "Coins"
Coins.Value = Data:GetAsync(player.UserId) or 0
end)
game.Players.PlayerRemoving:Connect(function(player)
Data:SetAsync(player.UserId, Coins.Value)
end)
It is also very helpful to add a connection to the game’s Close event, in case of server-shutdowns and what-not. Learn more about Closehere.
local DataStoreService = game:GetService("DataStoreService")
local Data = DataStoreService:GetDataStore("CoinsData")
game.Players.PlayerAdded:Connect(function(player)
local Coins = Instance.new("IntValue", player)
Coins.Name = "Coins"
Coins.Value = Data:getAsync(player.UserId) or 0
end)
game.Players.PlayerRemoving:Connect(function(player)
local Coins = player:FindFirstChild("Coins");
Data:GetAsync(player.UserId, Coins and Coins.Value or 0) -- Set to Coins.Value or 0 by default
end)
game:BindToClose(function()
-- save everyone's data
for i,v in pairs(game.Players:GetChildren()) do
if(v:FindFirstChild("Coins")) then
Data:SetAsync(v.UserId, v.Coins.Value);
end
end
end)
There are several things wrong with your code. Since you’re new to data stores that’s understandable. Roblox has an Onboarding program that gives tutorials in the different aspects of game development. They currently have one tutorial for game data called Saving Data | Roblox Creator Documentation. You should check it out, as it is very helpful.