How can I make a cash given on kill script? (That saves)

Hi, I am a rookie scripter, and I want to make a script where cash is given to you when you kill another player, but if you are on a different team then you are given cash each time you deal damage.

Something Similar to this:

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

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)
					end
				end
			end
		end
	end
end

-- Listen for player added events
game.Players.PlayerAdded:Connect(function(player)
	-- Listen for character added events
	player.CharacterAdded:Connect(function(character)
		-- Listen for player deaths
		character:WaitForChild("Humanoid").Died:Connect(function()
			OnPlayerDeath(character)
		end)
	end)
end)

But I am having trouble on making it save, and making it so the cash is given based on how much damage you have dealt.

I tried looking at some tutorials but I didn’t find any that worked for me so far.

Here’s my data saving script too, if needed.

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

Help would be appreciated!

1 Like

Okay so what is “creator” thats in the character humanoid does it say any error

2 Likes

Although this is slightly off topic from the main post, wouldn’t it make more sense to save your data when the data keys are changed, like when plr.Cash.Changed is fired? It seems like it would put unnecessary load on the datastore server by constantly uploading data instead of doing it only when necessary.

3 Likes

Creator is a tag is placed inside the humanoid of the player that was killed. And in that tag it has the name of the player that killed the other player, it helps the script identify who to give the cash to, that’s my best way of explaining it

2 Likes

oh, I wasn’t aware of that. I will try it

1 Like

You can make it only store the data when the player leaves the server

Here is a example

Game.Players.PlayerRemoving:Connect(function(player)
      -- datastore:SetAsync(plrKey, plrData) or whatever
end)
4 Likes

Like this?

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

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

local function LoadData(player)
	local plrKey = player.UserId
	local data = SaveData.Load(player)
	if data then
		player.leaderstats[currencyName.Value].Value = data.Cash
	end
end

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function(killed)
			local CreatorTag = character.Humanoid:FindFirstChild("creator")
			if CreatorTag and CreatorTag.Value then
				local stats = CreatorTag.Value:WaitForChild("leaderstats")
				stats["Cash"].Value = stats["Cash"].Value + 20
				SaveData(player) -- Save player data after each kill
			end
		end)
	end)
	LoadData(player)

	player.Removing:Connect(function()
		SaveData(player)
	end)
end)
1 Like

You don’t have to use a module

2 Likes

Well, my current data saving system does use a modulescript. Do I have to rewrite how the saving system works?

2 Likes

No but what’s the Module script?

2 Likes

OP showed the module script in the original post.

3 Likes

I’m asking so if he changed it anyway @Wultramn just make the module script do it once

2 Likes

Could you elaborate? Do I make the SaveData (& LoadData) ModuleScripts to do what once?

Anyway, here’s the SaveData and LoadData Module Scripts, I don’t know if LoadData is needed.

SaveData:

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

LoadData:

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

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


function LoadData(plr: Player)
	
	local plrKey = plr.UserId
	
	local dataFailedWarning = Instance.new("StringValue")
	dataFailedWarning.Name = "DATA FAILED TO LOAD"
	dataFailedWarning.Parent = plr

	local success, plrData = nil, nil
	
	while true do
		
		success, plrData = pcall(function()
			return datastore:GetAsync(plrKey)
		end)
		
		if not success then	
			warn("Error loading " .. plr.Name .. "'s (" .. plr.UserId .. ") data:\n" .. plrData)
			
		else
			break
		end
		
		task.wait(0.02)
	end
	
	dataFailedWarning:Destroy()

	return plrData
end

return LoadData

…I probably misunderstood the question.

2 Likes

I personally think that your SaveData code (modulescript and the playerremoving code) looks fine. As long as it works properly, it should be OK.

1 Like

Yeah, it works, but I am having trouble making the cash reward on killing players script to save using those scripts.

1 Like

Have you done debugging to make sure that the creator value is being set?

1 Like

Yes, the cash is being given. It just that you lose it when you rejoin, like. Your balance is set back to zero.

You still have the while loop ??

Oh, sorry about the misunderstanding. Is LoadData called at all? I don’t see any calls to it.

1 Like

Update: this error popped up.

19:49:13.867 Workspace.CashPerKillScript:9: attempt to index function with 'Load' - Server - CashPerKillScript:9