Datastores not working after teleporting to a another place

I have been trying to make it so that when you teleport to another place in the same game, it loads in the player leaderstats data(coins).

However, this doesn’t work and after coming back onto the main place, all the stats get reset.

I have looked on the forums, and I couldn’t understand any of the posts there or they weren’t relatable to my problem.

Could someone please help me out on what I am supposed to do? I am not asking for code, only for help on what to do as I didn’t get any solutions.

Here is my code:

Teleport Code:

local TPS = game:GetService("TeleportService")
local DSS = game:GetService("DataStoreService")
local CoinsDataStore = DSS:GetDataStore("CoinsDataStore")
local debounce = false

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		if not debounce then
			debounce = true
			local player = game.Players:GetPlayerFromCharacter(hit.Parent)
			if player then
				local PlayerId = "Player" .. player.UserId
				local success, errormessage = pcall(function()
					CoinsDataStore:SetAsync(PlayerId, player.leaderstats.Coins.Value)
				end)
				TPS:Teleport(18617802038, player)
				task.wait(5)
				debounce = false
			end
		end
	end
end)

Code on the teleported place:

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

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Parent = player
	leaderstats.Name = "leaderstats"
	
	local Coins = Instance.new("IntValue")
	Coins.Parent = leaderstats
	Coins.Name = "Coins"
	
	local PlayerId = "Player" .. player.UserId
	
	local success, errormessage = pcall(function()
		if CoinsDataStore:GetAsync(player.UserId) then
			Coins.Value = CoinsDataStore:GetAsync(PlayerId)
		else
			warn("No data!")
			Coins.Value = 0
			return
		end
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	local PlayerId = "Player" .. player.UserId
	local success, errormessage = pcall(function()
		CoinsDataStore:SetAsync(PlayerId, player.leaderstats.Coins.Value)
	end)
end)

I would be really grateful if anyone helps me out!

1 Like

Found the issue. At the teleported place, server is trying to find player.UserId key in the DataStore which is equal to nil but instead it needs to find PlayerId key which is equal to "Player" .. player.UserId. I hope it’ll help with your problem

1 Like

Ohh i guess im dumb tysm!! If i have any further issues i will check