Help with datastoreservice

Hello this is my first time using datastore and I’ve encountered a problem, the data does not saved at all. I already enabled studio access to api service and there is no error. pls help

code:

local DSS = game:GetService("DataStoreService")
local NightData = DSS:GetDataStore("NightData")

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

	local Night = Instance.new("IntValue")
	Night.Parent = leaderstats
	Night.Name = "Nights"
	
	local data
	local success , errormessage = pcall(function()
		data = NightData:GetAsync(player.UserId)
	end)
	
	if success then
		Night.Value = data
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local leaderstats = player:WaitForChild("leaderstats")
	local Night = leaderstats:WaitForChild("Nights")
	
	local success , errormessage = pcall(function()
		NightData:SetAsync(player.UserId, Night.Value)
	end)
end)

(btw I followed this Tutorial and this Tutorial. idk if it helps)

1 Like

I’ve had an issue where the server closed before the game could save the players data so I had added this at the end of my script.

game:BindToClose(function() task.wait(5) end)
3 Likes

that somehow works, Thanks dude!

This should work, there will be probablly a few errors because i wrote this in devforum not studio.

local stat = "Night" -- useless


local DataStore = game:GetService("DataStoreService")
local NightData = DataStore:GetDataStore("NightData")


game.Players.PlayerAdded:connect(function(player)
	local leader = Instance.new("Folder",player)
	leader.Name = "leaderstats"
	local Night = Instance.new("IntValue",leader)
	Night.Name = "Night"

	local data = {}
	local success, err = pcall(function()
		data = ds:GetAsync(player.UserId)
	end)
	if success then
		Night.Value = data[1]
	else
		warn(err)
	end
end)

game.Players.PlayerRemoving:connect(function(player)
	local success, err = pcall(function()
		ds:SetAsync(player.UserId, {player.leaderstats.Night.Value}
		)
	end)
end)
1 Like

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