Need help with fixing a cash reward on kill script

Hi, I made a cash reward on kill script from the help of my previous post. But my error wasn’t fully quite fixed, sometimes my cash does save, and sometimes it does not. Can someone help? It’d be GREATLY appreciated! : D (the SaveData ModuleScript was originally used for a shop system)

CashPerKill Script:

local conf = game.ReplicatedStorage:WaitForChild("Configuration")
local currencyName = conf:WaitForChild("CurrencyName")
local LoadData = require(game.ServerScriptService.ShopServer.ModuleScripts.LoadData)

local ShopServer = game.ServerScriptService:WaitForChild("ShopServer")
local SaveData = require(ShopServer.ModuleScripts:WaitForChild("SaveData"))

-- Function to give cash to the creator of the killed player and save data after each kill
local function OnPlayerDeath(character)
	local creatorTag = character.Humanoid:FindFirstChild("creator")
	if creatorTag and creatorTag.Value then
		local stats = creatorTag.Value:FindFirstChild("leaderstats")
		if stats then
			local cashStat = stats:FindFirstChild(currencyName.Value)
			if cashStat then
				cashStat.Value = cashStat.Value + 20 -- Reward the creator with 20 cash
				local player = game.Players:GetPlayerFromCharacter(character)
				if player then
					local success = SaveData(player) -- Save player data after each kill
					if success then
						print("Data saved successfully for player:", player.Name)
					else
						warn("Failed to save data for player:", player.Name)
					end
				end
			end
		end
	end
end

game.Players.PlayerAdded:Connect(function(player)
	-- Listen for character added events
	player:WaitForChild("leaderstats")
	local loadedData = LoadData(player)
	if loadedData then
		player.leaderstats:WaitForChild(currencyName.Value).Value = loadedData.Cash or 0
	end
	player.CharacterAdded:Connect(function(character)
		-- Listen for player deaths
		character:WaitForChild("Humanoid").Died:Connect(function()
			OnPlayerDeath(character)
		end)
	end)
end)

SaveData ModuleScript:

local conf = game.ReplicatedStorage:WaitForChild("Configuration")
local currencyName = conf:WaitForChild("CurrencyName")
local dsKey = conf:WaitForChild("DatastoreKey")

local dss = game:GetService("DataStoreService")
local datastore = dss:GetDataStore(dsKey.Value)

local rsModules = game.ReplicatedStorage:WaitForChild("ModuleScripts")
local GetTools = require(rsModules:WaitForChild("GetTools"))


function SaveData(plr: Player, equippedTool: string)

	if not plr:FindFirstChild("DATA FAILED TO LOAD") then
		
		local plrKey = plr.UserId

		local plrCash = plr.leaderstats[currencyName.Value].Value
		
		local plrTools = GetTools(plr, {equippedTool})
		
		local plrData = {Cash = plrCash, Tools = plrTools}
		
		local success, err = nil, nil
		
		while true do
			
			success, err = pcall(function()
				datastore:SetAsync(plrKey, plrData)
			end)
			
			if not success then
				warn("Error saving " .. plr.Name .. "'s (" .. plr.UserId .. ") data:\n" .. err)
				
			else
				break
			end
			
			task.wait(0.02)
		end
		
	else
		warn("Error saving " .. plr.Name .. "'s (" .. plr.UserId .. ") data:\nData failed to load on joining.")
	end
end

return SaveData

In the OnPlayerDeath function, you’re calling SaveData(player) without passing any arguments related to the equipped tool. However, in your SaveData function, you’re expecting an argument equippedTool. If the equippedTool argument is not provided, the function might not save the data properly.

So to address this issue, you can modify the OnPlayerDeath function to pass the equipped tool as an argument to the SaveData function, try this version of your script!

local function OnPlayerDeath(character)
    local creatorTag = character.Humanoid:FindFirstChild("creator")
    if creatorTag and creatorTag.Value then
        local stats = creatorTag.Value:FindFirstChild("leaderstats")
        if stats then
            local cashStat = stats:FindFirstChild(currencyName.Value)
            if cashStat then
                cashStat.Value = cashStat.Value + 20 -- Reward the creator with 20 cash
                local player = game.Players:GetPlayerFromCharacter(character)
                if player then
                    local equippedTool = "Sword"  -- Adjust this to match the name of the equipped tool
                    local success = SaveData(player, equippedTool) -- Save player data after each kill
                    if success then
                        print("Data saved successfully for player:", player.Name)
                    else
                        warn("Failed to save data for player:", player.Name)
                    end
                end
            end
        end
    end
end

Additionally ensure that the equippedTool argument is passed correctly when calling the SaveData function in other parts of your code, this should help ensure that the data is saved properly after each kill. Lmk if it worked!:slightly_smiling_face:

1 Like

I am so sorry that I forgot to specify this but I originally used the SaveData script for a shop system, will it still work if I do use that SaveData script for the cash reward on kill script? Or should I scrap it entirely and make a new saving system?

Ofc it can. If the script is well-structured and flexible enough to accommodate these changes, you can reuse it for the cash reward system. However, if significant modifications are needed or if the current script is tightly coupled to the shop system, it may be more practical to develop a separate saving system specifically tailored for the cash reward system.

1 Like

Okay then, thank you very much! :smiley:

1 Like