Datastore is not working

I have tried everything, but this datastore seems to be working, all I want is to save a intvalue, to a datastore, and yes. I do have http enabled. There are also no errors in the output whatsoever. I am not sure if it is obvious and I am just overthinking it, but i could really use some help. Thanks!

local DS =  game:GetService("DataStoreService"):GetDataStore("TotalDS")


game.Players.PlayerAdded:Connect(function(plr)
	

	local TotalDistanceWalked = Instance.new("IntValue")
	TotalDistanceWalked.Parent = plr:WaitForChild("leaderstats")
	TotalDistanceWalked.Name = "Total"
	
	local data
	local key = "Player_".. plr.UserId
	
	local success, errormessage = pcall(function()
		data = DS:GetAsync(key)
	end)
	
	if success then
		TotalDistanceWalked.Value = data
	elseif data == nil then
		TotalDistanceWalked.Value = 0
	else
		warn(errormessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local key = "Player_".. player.UserId

	local data = player.leaderstats.Total.Value

	DS:SetAsync(key, data)
end)
1 Like

You’re ignoring the potential error message completely:

	local data
	local key = "Player_".. plr.UserId
	
	local success, errormessage = pcall(function()
		data = DS:GetAsync(key)
	end)
	
	if success then
		TotalDistanceWalked.Value = data
	elseif data == nil then
		TotalDistanceWalked.Value = 0
	else
		warn(errormessage)
	end

If we succeed, use the data.
Otherwise if our data is nil, use 0.

Your third branch is never going to happen, because both possible cases already happened.

Try this instead and see if you get a previously hidden error:

local success, output = pcall(function()
    return DS:GetAsync(key)
end)

if success then
    TotalDistanceWalked.Value = output -- `nil` here is fine, since it's going to cast to 0 anyway
else
    warn(output)
end

Furthermore, you’re certain leaderstats is being created by something else, right?

1 Like

Oh yes thank you, it works! I will mark this as the solution. I much appreciate your help.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.