Hi, I am trying to make a script that gives cash to the player that kills another player, using a tutorial, but I am having trouble on making it so the cash saves when you leave & rejoin the game. And there weren’t any good or functioning tutorials that I know of to fix an error like that.
Help would be really appreciated.
CashPerKill Script:
local conf = game.ReplicatedStorage:WaitForChild("Configuration")
local currencyName = conf:WaitForChild("CurrencyName")
-- Load the save data module script
local saveDataModule = require(game.ServerScriptService.ShopServer.ModuleScripts.SaveData)
-- Load the load data module script
local loadDataModule = require(game.ServerScriptService.ShopServer.ModuleScripts.LoadData)
game.Players.PlayerAdded:Connect(function(player)
-- Load the player's saved cash value when they join
local savedData = loadDataModule(player)
if savedData then
local stats = player:WaitForChild("leaderstats")
stats[currencyName.Value].Value = savedData.Cash
end
-- Function to update the player's cash value
local function updateCash(killer)
local stats = killer:WaitForChild("leaderstats")
stats[currencyName.Value].Value = stats[currencyName.Value].Value + 20
-- Save the updated cash value
saveDataModule.SaveData(killer)
end
-- Connect the updateCash function to the Humanoid's Died event
player.CharacterAdded:Connect(function(character)
character:WaitForChild("Humanoid").Died:Connect(function()
local CreatorTag = character.Humanoid:FindFirstChild("creator")
if CreatorTag and CreatorTag.Value then
local killer = CreatorTag.Value
updateCash(killer)
end
end)
end)
end)
SaveData Script:
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