Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to stop leaderstat script looping multiple times?

So, I have an obby in my game that at the end gives you ten tokens, which is a leaderstat, but it repeats multiple times when it is touched, ending up giving over 50 points each time. Is there a way to make it only give the tokens once instead of multiple?

function OnTouched(Part)
	local player = game.Players:GetPlayerFromCharacter(Part.Parent)
	if player then
		local leaderstats = player:FindFirstChild("leaderstats")
		if leaderstats then
			leaderstats.Tokens.Value = leaderstats.Tokens.Value + 10
		end
	end
end

script.Parent.Touched:Connect(OnTouched)

1 answer

I recommend instead of making the player not be able to touch it again (because player wont be able to touch it if they complete obby again) you should instead teleport the player back to the start, I've wrote code for both. just use whichever one fits you best.

One time use:

local playersThatCanTouch = {}
local players = game:GetService("Players")

players.PlayerAdded:Connect(function(player)
	table.insert(playersThatCanTouch, player)
end)

function OnTouched(Part)
	local character = Part.Parent
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		local player = players:GetPlayerFromCharacter(character)
		if table.find(playersThatCanTouch, player) then
			table.remove(playersThatCanTouch, table.find(playersThatCanTouch, player))
			local leaderstats = player:FindFirstChild("leaderstats")
			if leaderstats then
				leaderstats.Tokens.Value += 10
			end
		end
	end
end

script.Parent.Touched:Connect(OnTouched)

Teleport:

local players = game:GetService("Players")
local debounce = 0.5
local debounceEnabled = false

function OnTouched(Part)
	local character = Part.Parent
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		if debounceEnabled == false then
			debounceEnabled = true
			
			character:MoveTo(Vector3.new(0, 0, 0)) -- put starting point position in here
			
			task.wait(debounce)
			debounceEnabled = false
		end
	end
end

script.Parent.Touched:Connect(OnTouched)

4 comments

0

It works! Thanks.

0

Ive actually realised that this is essentially the same teleport script i had already. It still gives the points multiple times before teleporting.

0

Thats what debounce is for, it makes it so you cannot touch the part for however long you set debounce for, meaning that it should solve the multiple points problem.

0

Yeah, but it seems to still do that, so im assuming I increase debounce?

This discussion is preserved as it was. New answers, comments, and votes are closed.