Leaderstats saving both as the same number

Hello wonderful people,

I have a script here that is a leaderstats script and also a stage script (for an obby) and when it saves the stats it saves both the leaderstats as the same thing how do I save them to themselves?

    local checkpoints = workspace.checkpoints

    local datastore = game:GetService("DataStoreService"):GetDataStore("Stage")

    game.Players.PlayerAdded:Connect(function(player)
    	local leaderstats = Instance.new("Model")
    	leaderstats.Name = "leaderstats"
    	leaderstats.Parent = player

    	local stage = Instance.new("IntValue")
    	stage.Value = datastore:GetAsync(player.UserId, stage.Value) or 1
    	stage.Name = "Stage"
    	stage.Parent = leaderstats
    	local coins = Instance.new("IntValue")
    	coins.Value = datastore:GetAsync(player.UserId, coins.Value) or 0
    	coins.Name = "Coins"
    	coins.Parent = leaderstats

    	player.CharacterAdded:Connect(function(character)
    		local humanoid = character:WaitForChild("Humanoid")

    		wait(character:MoveTo(checkpoints[stage.Value].Position))
    		character:MoveTo(checkpoints[stage.Value].Position)

    		humanoid.Touched:Connect(function(part)
    			if part.Parent == checkpoints then
    				if tonumber(part.Name) == stage.Value + 1 then
    					stage.Value = stage.Value + 1
    				end
    			end
    		end)
    	end)
    end)

    game.Players.PlayerRemoving:Connect(function(player)
    	local success, errormessage = pcall(function()
    		datastore:SetAsync(player.UserId, player.leaderstats.Stage.Value)
    		datastore:SetAsync(player.UserId, player.leaderstats.Coins.Value)
    	end)
    	if success then
    		print("saved stage for " .. player.Name)
    	else
    		warn(errormessage)
    	end
    end)

    game.Chat.BubbleChatEnabled = true
    game.Players.RespawnTime = 0

Try saving using a table instead of one value. For example, you would save using:

local saveTable = {
    Stage = stats.Stage.Value,
    Coins = stats.Coins.Value
}
local success, errormessage = pcall(function()
    datastore:SetAsync(player.UserId, saveTable)
end)

Then, to access the save you would do this:

local saveFile
local success, errormessage = pcall(function()
    saveFile = datastore:GetAsync(player.UserId)
end)

if success then
    -- Make the intValue instances and stuff
    if saveFile then
        stage.Value = saveFile.Stage
        coins.Value = saveFile.Coins
    end
else
    print("Save data could not be loaded for " .. player.Name)
end
1 Like

Are the datastores both named Stage?