DataStores not working!

hi! i am made a npc that when you kill you recieve 8000 cash but, i am trying to save the data but it dosent work! here is the code for datastore:

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

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

	wait()

	local plrkey = "id_"..plr.userId

	local savevalue = plr.leaderstats.cash

	local GetSaved = datastore:GetAsync(plrkey)

	if GetSaved then

		savevalue.Value = GetSaved[1]

	else

		local NumbersForSaving = {savevalue.Value}

		datastore:GetAsync(plrkey, NumbersForSaving)

	end

end)

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

	datastore:SetAsync("id_"..plr.userId, {plr.leaderstats.cash.Value})

end)

leaderstats:

game.Players.PlayerAdded:Connect(function (plr)
	local stats = Instance.new("BoolValue",plr)
	stats.Name = "leaderstats"

	local cash = Instance.new("IntValue",stats)
	cash.Name = "Money"
	cash.Value =100 --how much you want to start with
end)

when i beat the enemy i get 8000 money but when i exit and play again i start with the initial money

1 Like

try this instead:

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

game.Players.PlayerAdded:Connect(function(plr)
	local plrkey = "id_"..plr.userId
	local savevalue = plr.leaderstats.cash

	local suc,err = pcall(function()
		local GetSaved = datastore:GetAsync(plrkey)
		
		if GetSaved then
			savevalue.Value = GetSaved[1]
		else
			local NumbersForSaving = {savevalue.Value}
			datastore:SetAsync(plrkey, NumbersForSaving)
			savevalue.Value = NumbersForSaving[1]
		end
	end)
	
	if err then
		warn(err)
	end

end)

game.Players.PlayerRemoving:Connect(function(plr)
	datastore:SetAsync("id_"..plr.userId, {plr.leaderstats.cash.Value})
end)
2 Likes

didn`t work i tried in the roblox game client.

2 Likes

DataStore don’t work on the client side, you have to use a normal script.

2 Likes

i did. i also tried to enable the api security but it didnt work

1 Like

looks like it is working now! the money giving script was wrong because i wrote .Money instead of .cash . Thanks @BankrollAbd for your help :slight_smile:

2 Likes

If your problem is solved, mark your message as solved.

Nice try, trying to save data when the LAST player in the server leaves, won’t work. The server only has like half a second left to live., so the data may not save.
I’ve had a bad experience with this before.

i made my comment the solution because i found the solution while testing

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