Code support - touched part gives money

Hello! I need some help with the code, I need to make when touching this part the money of my leaderstats change.

image

ServerScript code:

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Parent = leaderstats
	
	local data
	
	local success, errormessage = pcall(function()
		data = myDataStore:GetAsync(player.UserId.."-cash")
	end)
	
	if success then
		cash.Value = data
	else
		print("There was an error with getting your data.")
		wait(errormessage)
	end
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	
	local success, errormessage = pcall(function()
		myDataStore:SetAsync(player.UserId.."-cash", player.leaderstats.Cash.Value)
	end)
	
	if success then
		print("Player data successfully saved!")
	else
		print("There was an error when saving data.")
		warn(errormessage)
	end
end)

Script (Part script):

script.Parent.Touched:Connect(function()

-- When you touch this part it will give you cash

end)

Could someone help me with that, please? :frowning:

1 Like
local Player = game:GetService("Players")

script.Parent.Touched:Connect(function(hit) --- Object that hits the part
   local PlayerCharacter = Player:GetPlayerFromCharacter(hit.Parent) -- Get the player that hits the part
   local Leaderstats = PlayerCharacter:WaitForChild("leaderstats")
--- Reward goes here. 
end)
1 Like

It did not working :frowning:

You have to place what you want to add to the datastore for the player at ---Reward goes here.

i did and got an error :frowning:

That’s because cash doesn’t exist as a variable in that script. Declare it and reference it properly and you’ll be fine.

That’s because it’s a example I shown you. Past line 7 is where you code the reward you wanna to give the player.
Like this:

local Player = game:GetService("Players")

script.Parent.Touched:Connect(function(hit) --- Object that hits the part
   local PlayerCharacter = Player:GetPlayerFromCharacter(hit.Parent) -- Get the player that hits the part
   if PlayerCharacter then
       local Leaderstats = PlayerCharacter:WaitForChild("leaderstats")
       --- Reward goes here. 
       Leaderstats.Cash.Value =  Leaderstats.Cash.Value + --value
    end
end)
2 Likes

It worked! Thank you very much :smiley: