Hi. I am having an issue with data store. I have made a datastore script that saves when you enter and leave. This works fine, however when I purchase something with the shop, it works fine up until I rejoin the game where the points initially deducted from the shop have came back. For example, if I have 30 coins, I purchase an item for the shop for 10 coins. I now have 20 coins. However, when I rejoin, I once again have 30 coins. Any help with this would be appreciated.
DataStore script
local DataStore = game:GetService("DataStoreService"):GetDataStore("leaderStorage")
game.Players.PlayerAdded:connect(function(player)
local stats = Instance.new("IntValue",player)
stats.Name = "leaderstats"
local Wins = Instance.new("IntValue",stats)
Wins.Name = "Wins"
local Coins = Instance.new("IntValue",stats)
Coins.Name = "Coins"
local key = "player-"..player.userId
local savedValues = DataStore:GetAsync(key)
if savedValues then
-- save format: (wins,coins)
Wins.Value = savedValues[1]
Coins.Value = savedValues[2]
else
local valuesToSave = {Wins.Value, Coins.Value}
DataStore:SetAsync(key,valuesToSave)
end
end)
game.Players.PlayerRemoving:connect(function(player)
local key = "player-"..player.userId
-- save key(wins, coins)
local valuesToSave = {player.leaderstats.Wins.Value, player.leaderstats.Coins.Value}
DataStore:SetAsync(key, valuesToSave)
end)
Shop script (game>StarterGui(PlayerGui)>ScreenGui>Frame>TextButton>LocalScript(Shop Script)) ItemName and Price are children of the TextButton, ItemName is a string value while Price is an integer value.
local player = game.Players.LocalPlayer
local leaderboard = player:WaitForChild("leaderstats")
local button = script.Parent
local price = button:WaitForChild("Price")
local item = button:WaitForChild("ItemName")
local rs = game:GetService("ReplicatedStorage")
button.MouseButton1Click:connect(function()
if player.ItemStorage:FindFirstChild(item.Value)or player.Character.Torso:FindFirstChild(item.Value)then
return
elseif
leaderboard.Coins.Value >= price.Value then
leaderboard.Coins.Value = leaderboard.Coins.Value - price.Value
local item = rs:FindFirstChild("PurchasableItems"):WaitForChild(item.Value)
item:Clone().Parent = player.StarterGear
item:Clone().Parent = player.Character.Torso
end
end)

1 comment
Thanks!