How do I change leaderstat value from touch?

Solved, although I don’t know which post I should mark as solution.

Hi all,

I’m wondering how to change the value of a leaderstat from the part the script comes from being touched. What I’m trying to say, is that I want that, when a part is touched, the leaderstat changes. However, I don’t know how to script that because I just started learning Lua.

I haven’t tried solutions since I don’t know how to script, but I used the DevForum tutorials. Instead of gold though, I changed it to “water”.

Can you please help? Thanks.

1 Like

here is a script:

 local part = ----your part
part.Touched:connect(function(hit)
if hit:GetPlayerFromCharacter(hit.Parent) then
local plr = hit:GetPlayerFromCharacter(hit.Parent)
plt.leaderstats.coins =  -------here you can change the value that is parented to the leaderstats change the coins variable its just an example
end)

Have a look at this:
https://education.roblox.com/en-us/resources/adventure-game-creating-a-leaderboard
It will help you and includes scripts to achieve what you want to do as well as explaining things properly.

Follow up by reading the official Roblox Education site.

To help out, the Touched event returns the part that hit the part connected to a touched event, you can then get the player from the parent of what hit the part via game.Players.GetPlayerFromCharacter(hit.Parent), where hit is the name of the thing that is returned from Touched, and then do some changes from there. You will also need a debounce to prevent spamming, my recommendation is a Table debounce so the wait will not affect everyone

An example would be this

local part = script.Parent
local debs = {}

part.Touched:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	if not plr or debs[plr.Name] then return end
	debs[plr.Name] = true
	local value = plr.leaderstats.Coins --Change Coins with name of value
	value.Value += 5
	wait(1)
	debs[plr.Name] = nil
end)

When something touches part, check if a player can be gotten from it, if a player was not found or the key in that dictionary of debounces with the name of the player is true, then stop the function. If neither were met, get the value you want to change and add 5 to it, wait a seecond, and allow the player to use it again

3 Likes