DataStore not working as intended

I am trying to save the stage of a player in an obby game, and teleporting the player to the stage they left off at.

However, it’s not working and keeps saving nil. I believe the problem lies with the SaveAync() part as it’s not printing whether it failed or succeeded.

I tried looking up datastores on the developer page just to confirm that I wasn’t doing anything wrong, but I couldn’t find anything I might have been doing wrong. Furthermore, I also contacted a few friends of mine who are programmers as well so that they can

Here’s the script:

local DataStoreService = game:GetService(“DataStoreService”)
local StageDataStore = DataStoreService:GetDataStore(“StageDataStore”)
local Players = game:GetService(“Players”)
local PlayerHasPlayedBefore = false

Players.PlayerRemoving:Connect(function(Player)

print("Player is leaving!")

local Success, Fail = pcall(function()
	StageDataStore:SetAsync("Player - "..Player.UserId, Player.leaderstats.Stage.Value)
end)


if Success then
	print("Data saved successfully!")
else 
	print("Failed!")
end

print(Player.leaderstats.Stage.Value)

end)

Players.PlayerAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function(Character)

	local Stage

	local Success, Fail = pcall(function()
		Stage = StageDataStore:GetAsync("Player - "..Player.UserId, Player.leaderstats.Stage.Value)
		print(Stage)
	end)
	
	if Success and Stage ~= nil then

		print("Data loaded successfully!")
				
		Player.leaderstats.Stage.Value = Stage

		print(Stage)
		
		for i,v in pairs(game.Workspace.Checkpoints:GetChildren()) do
			if v.Value.Value == Stage then
				Character:WaitForChild("HumanoidRootPart").CFrame = v.CFrame
			end
		end


	end
end)

end)

Ive never seen a key with hyphen But underscore Player_..
im not sure if this is related to the problem

btw try getting the value from the function

Thanks for clarifying vv

1 Like

Sometimes when the last person in game leaves the server closes too fast and doesn’t have enough time to save, try putting this in another script:

game:BindToClose(function()
	if game:GetService("RunService"):IsStudio()then 
		wait(6) 
	else
		wait(35)
	end
end)
1 Like

I don’t see the point of returning Stage as GetAsync should do the same thing, as for the hyphen thing, it doesn’t matter what you put in as long as it’s different for each player, it’s just a key.

1 Like

Hmm, I’ll try testing this out in game, if it saves in game and not in studio, then it means that you are right and it’s closing before it has enough time to save.

Ok I just tried it in game and it works perfectly, thank you so much. You were correct, studio closes the server toon quickly before it even has time to save the data.

1 Like

No problem! I’m glad I could be of some help. :smiley:

1 Like