Autosave not saving on Deaths

Hello! I am making a sword game. and I have been working on a tier system which works beautifully, but my autosave for the tools that have been upgraded to work doesn’t work fully. It works on multiple play sessions but when you respawn or get killed it wont save anything. so in a way it wipes your data. If you need more info feel free to contact thank you.

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local swordDataStore = DataStoreService:GetDataStore("SwordTierData")
local swordsFolder = ServerStorage:WaitForChild("TieredSwords")
local updateGUIEvent = ReplicatedStorage:WaitForChild("ToolEvents"):WaitForChild("UpdateSwordGUI")

local supportedSwords = { "SanctumVendetta", "Excalibur", "Katana" }

local function getSwordBaseName(toolName)
	for _, base in ipairs(supportedSwords) do
		if toolName == base or toolName:match("^" .. base .. "_Tier%d+") then
			return base
		end
	end
	return nil
end

-- Save all swords player owns from Backpack and Character
local function saveSwordData(player)
	if not player then return end

	local owned = {}

	local function checkTools(container)
		for _, tool in ipairs(container:GetChildren()) do
			if tool:IsA("Tool") then
				local base = getSwordBaseName(tool.Name)
				if base then
					owned[base] = tool.Name -- Save exact sword tiered name
				end
			end
		end
	end

	local backpack = player:FindFirstChild("Backpack")
	local character = player.Character

	if backpack then checkTools(backpack) end
	if character then checkTools(character) end

	if next(owned) == nil then
		print("[SwordSaveHandler] No swords found to save for", player.Name)
	else
		print("[SwordSaveHandler] Saving swords for", player.Name, ":", owned)
	end

	local success, err = pcall(function()
		swordDataStore:SetAsync("Sword_" .. player.UserId, owned)
	end)
	if not success then
		warn("[SwordSaveHandler] Failed to save sword data for", player.Name, ":", err)
	else
		print("[SwordSaveHandler] Successfully saved swords for", player.Name)
	end
end

-- Load swords from DataStore and give to player
local function loadSwordData(player)
	if not player then return end

	local success, saved = pcall(function()
		return swordDataStore:GetAsync("Sword_" .. player.UserId)
	end)

	if not success then
		warn("[SwordSaveHandler] Failed to load sword data for", player.Name)
		return
	end

	if not saved or type(saved) ~= "table" or next(saved) == nil then
		print("[SwordSaveHandler] No saved swords found for", player.Name)
		return
	end

	print("[SwordSaveHandler] Loading swords for", player.Name, ":", saved)

	-- Delay load slightly to ensure Backpack is ready
	task.spawn(function()
		local backpack = player:WaitForChild("Backpack", 10)
		if not backpack then
			warn("[SwordSaveHandler] Backpack not found for", player.Name)
			return
		end

		for baseName, fullSwordName in pairs(saved) do
			local swordTemplate = swordsFolder:FindFirstChild(fullSwordName)
			if swordTemplate then
				local clone = swordTemplate:Clone()
				clone.Parent = backpack

				local tier = tonumber(fullSwordName:match("Tier(%d+)")) or 0
				updateGUIEvent:FireClient(player, baseName, tier)
			else
				warn("[SwordSaveHandler] Sword template missing:", fullSwordName)
			end
		end
	end)
end

-- Setup save/load connections for each player
Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		-- On respawn, load swords with delay
		task.delay(1, function()
			loadSwordData(player)
		end)

		-- Save swords on character death for extra safety
		local humanoid = character:WaitForChild("Humanoid", 10)
		if humanoid then
			humanoid.Died:Connect(function()
				saveSwordData(player)
			end)
		end
	end)

	-- Save swords on character removal (reset)
	player.CharacterRemoving:Connect(function()
		saveSwordData(player)
	end)
end)

-- Save swords on player leaving the game
Players.PlayerRemoving:Connect(function(player)
	saveSwordData(player)
end)

-- Save all players on server shutdown
game:BindToClose(function()
	for _, player in pairs(Players:GetPlayers()) do
		saveSwordData(player)
	end
end)
1 Like

I tried your script out, I think think the problem resides in trying to save the player’s data multiple times when the player dies, causing the data to be wiped. You could find some way to ensure that saveSwordData() only fires once every time a player resets/leaves, or you could remove the .Died and .CharacterRemoving events entirely, and instead save the player’s data whenever a new item is added to their Backpack. That way, their data is already loaded every time they respawn, and you are only updating it when it changes or when they leave.

2 Likes

Thank you i will try this when i get access to my computer [EDIT: Thank you so much it works amazingly now!]

1 Like

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