Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I make this leaderstats script save?

I have got this leaderstats script that works fine. I just need a way of saving it when a player leaves the game. I'm not very good with DataStores.

game.Players.PlayerAdded:connect(function(player)
	local Stats = Instance.new("Model", player)
	Stats.Name = "leaderstats"
	local Timer = Instance.new("IntValue", Stats)
	Timer.Name = "Minutes Staring"
	Timer.Value = 0
	while true do 
		wait (60)
		Timer.Value = Timer.Value + 1
	end
end)

1 answer

✓ Accepted answer

Your answer is DataStores but as you mentioned you're not very good with them I won't fully explain (I'll leave a link) but I will explain a little bit.

local dataStoreService = game:GetService("DataStoreService")
local timeData = dataStoreService:GetDataStore("TimerValue")

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

    local Timer = Instance.new("IntValue", Stats)
    Timer.Name = "Minutes Staring"
    Timer.Value = timeData:GetAsync(player.UserId) or 0

    while true do 
        wait (60)
        Timer.Value = Timer.Value + 1
    end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local timerValue = player.leaderstats["Minutes Starting"]
	timeData:SetAsync(player.UserId, timerValue.Value)
end)

OK so basically this works by creating a new datastore called TimerValue and when someone joins our game we get that current value that's in the storage by using GetAsyc and player.UserId. The reason we use or 0 is because they may not have a timer value set in the datastore yet so we default it to 0. When we set the async when the player is leaving we use SetAsync to replace the value with the new time. Here we are using the player's user id as the key but you can use anything like "TIME_PLAYED" anything.

And remember :Connect() not :connect()

Learn more about data stores here!

1 comment

0

Thank you! Very helpful!

This discussion is preserved as it was. New answers, comments, and votes are closed.