Teleport to a new place and retain datastores

I have a script to save a player’s backpack to a datastore and it works fine inside my game, but when a player teleports to another place inside my game, their backpack reverts back to when they joined the game. I am not sure if I should save the data on teleport or pass the data as a parameter or how I would go about doing either of those.

I also have three teams and when a player teleports, they do not stay on the same team. They join the autoassign team. (This is a neutral team between the two warring teams)

Here is the datastore script:

local ds = game:GetService("DataStoreService"):GetDataStore("ToolSave2")
game.Players.PlayerAdded:connect(function(plr)
	local Key = "id-"..plr.userId
	pcall(function()
		local tools = ds:GetAsync(Key)
		if tools then
			for i,v in pairs(tools) do
				local tool = game.ReplicatedStorage.Items:FindFirstChild(v)
				if tool then
					tool:Clone().Parent = plr:WaitForChild("Backpack")
					tool:Clone().Parent = plr:WaitForChild("StarterGear")
				end
			end
		end
	end)
end)
game.Players.PlayerRemoving:connect(function(plr)
	local Key = "id-"..plr.userId
	pcall(function()
		local toolsToSave = {}
		for i,v in pairs(plr.Backpack:GetChildren()) do
			if v then
				table.insert(toolsToSave,v.Name)
			end
		end
		ds:SetAsync(Key,toolsToSave)
	end)
end)

and here is one of the telport scripts:

local TeleportService = game:GetService("TeleportService")
 
local placeID_1 = 5004169251  -- desert zone
local placeID_2 = 4951521502   -- lobby
 
local function onPartTouch(otherPart)
	local player = game.Players:GetPlayerFromCharacter(otherPart.Parent)
	if player then
		TeleportService:TeleportToSpawnByName(placeID_1, "Hell", player)
	end
end
script.Parent.Touched:Connect(onPartTouch)
1 Like