Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to stop leaderstat script looping multiple times?

Asked by 1 year ago

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

Log in to vote
0
Answered by
Atzlk 0
1 year ago

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)
0
It works! Thanks. NightminerYT 2 — 1y
0
Ive actually realised that this is essentially the same teleport script i had already. It still gives the points multiple times before teleporting. NightminerYT 2 — 1y
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. Atzlk 0 — 1y
0
Yeah, but it seems to still do that, so im assuming I increase debounce? NightminerYT 2 — 1y
Ad

Answer this question