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

Repeat block of code while button is held on a block?

Asked by
nicros 165
8 years ago

so thanks for the user Ryzox i have a working script that gives gold when u click on a block....and im using it for a super simple fishing system, but im wanting it to repeat giving gold while you are holding click on the block if it makes sense.....

im very noob at lua so i have no clue how to do this. i know its probably going to use the While repeat but idk how to add that along with while mouse button is down or w/e and help would be appreciated :)

here is the script ive got

script.Parent.ClickDetector.MouseClick:connect(function(player)
    local Leaderstats = player:findFirstChild("leaderstats")
    if Leaderstats:findFirstChild("Gold") then
            --Below needs to repeat while left mouse button is held down on the block
            Leaderstats.Gold.Value = Leaderstats.Gold.Value + 10
            --Above needs to repeat while left mouse button down on the block
    end
end)

1 answer

Log in to vote
1
Answered by 8 years ago

The Click Detector itself does not have an event (E.G "MouseClick" in your code there) However the MouseClick event gives a player object and inside that there is a function (E.G "FindFirstChild") called "GetMouse" which returns a "PlayerMouse" object which does have an event to detect when the mouse buttons are released.

script.Parent.ClickDetector.MouseClick:connect(function(player) --The clickdetector event gives a player object.
    local leftMouseDown = true
    player:GetMouse().Button1Up:connect(function() 
        leftMouseDown = false --When the left mouse button is released then the loop will be stopped.
    end) 
    while leftMouseDown do --This is equal to "while leftMouseDown == true do". This basically means that while the leftMouseDown variable is true then run the code inside
        player.leaderstats.Gold.Value = player.leaderstats.Gold.Value + 10 --This adds the 10 gold to the leaderstats
        wait(1) --This means that the loop waits 1 second before adding another 10 gold
    end
end)

This code does assume that the "leaderstats" and the "Gold" Instances already exist. Meaning that if they don't then the code will error.

I added them in like so:

game.Players.PlayerAdded:connect(function(player) --Called whenever a player joins the game
    local leaderstats = Instance.new("Model")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
    local gold = Instance.new("IntValue")
    gold.Name = "Gold"
    gold.Parent = leaderstats
end)

Hope this was what you was looking for.

0
omg ty so much, this is exactly what i was looking for :) nicros 165 — 8y
Ad

Answer this question