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