I want to make something have an automatic value when you join the game, and you can change the value in shops. But when I join, it sets the value, and then loads in 0 because it saved 0 from when I leave the game. Is there a way to fix this?
Script:
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
-----------------Loading Data------------------
game.Players.PlayerAdded:Connect(function(player)
--Upgrades
local Upgrades = Instance.new("Folder")
Upgrades.Name = "Upgrades"
Upgrades.Parent = player
local Multiplier = Instance.new("IntValue")
Multiplier.Name = "Multiplier"
Multiplier.Value = 1
Multiplier.Parent = Upgrades
local MultPrice = Instance.new("IntValue")
MultPrice.Name = "MultiplierPrice"
MultPrice.Value = 10
MultPrice.Parent = Multiplier
local Backpack = Instance.new("IntValue")
Backpack.Name = "Backpack"
Backpack.Value = 5
Backpack.Parent = Upgrades
local BpPrice = Instance.new("IntValue")
BpPrice.Name = "BackpackPrice"
BpPrice.Value = 10
BpPrice.Parent = Backpack
local playerUserId = player.UserId
--Load Data
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(playerUserId)
end)
if success then
if data then
for i, v in pairs(Upgrades:GetChildren() and Upgrades:GetDescendants()) do
for dataValue, _ in pairs(data) do
if dataValue == v.Name then
v.Value = dataValue
end
end
end
end
-- Set our data equal to the current Cash
end
--pcalls protect you from getting errors.
end)
-----------------------Saving Data-------------------------
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = player.UserId
local data = {}
for i, v in ipairs(player.Upgrades:GetChildren() and player.Upgrades:GetDescendants()) do
data[v.Name] = v.Value
end
local success, errormessage = pcall(function()
myDataStore:UpdateAsync(playerUserId, function(oldData)
local previousData = oldData or {DataId = 0}
if data.DataId == previousData.DataId then
return data
else
return nil
end
end)
end)
end)