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

How to make it when a button is pressed, it runs the script only once?

Asked by 2 years ago

Hello, i am currently working on a game, and i would like to know how to make a script only run once. What i mean by that is i don't want to use debounce, since debounce is more of a timer for the script to then run again. I only want this, press a button, it runs the script, then you can't press it again, but the other players who haven't pressed the button yet can press it. Here is my code.

local water = script.Parent.Parent.Parent.water
local switch = script.Parent

function move(x, y ,z)
    for i = 1,10 do
        water.Position = water.Position + Vector3.new(x, y ,z)
        wait(0.01)
    end
end

function onClick()
    switch.LaserFire:Play()
    switch.BrickColor = BrickColor.new("Bright green")
    switch.Size = Vector3.new(1, 0.211, 2.049)
    move(-1.1,0,0)
    return
end

script.Parent.ClickDetector.MouseClick:Connect(onClick)
0
Thank you so much! I'll try to learn more about attributes. Thanks for your help! :D Birdoman7798 -3 — 2y

1 answer

Log in to vote
0
Answered by
imKirda 4491 Moderation Voter Community Moderator
2 years ago

Try using attributes, attributes are like custom properties, when player clicks the button you :SetAttribute called "PressedButton" (custom property name) to true and when someone presses the button, you check if :GetAttribute called "PressedButton" is already true, if so then return from the function:

local water = script.Parent.Parent.Parent.water
local switch = script.Parent

-- prefer using "local", same rules applied as with using "local" on
-- non-function variables
local function move(x, y ,z)
    for i = 1,10 do
        water.Position = water.Position + Vector3.new(x, y ,z)
        wait(0.01)
    end
end

-- MouseClick passes a first parameter which is the player who clicked it
-- we are going to put attributes on this player
local function onClick(player)
    if player:GetAttribute("PressedButton") then
        return -- return (stop the function) since he already clicked the button
    end

    player:SetAttribute("PressedButton", true)

    switch.LaserFire:Play()
    switch.BrickColor = BrickColor.new("Bright green")
    switch.Size = Vector3.new(1, 0.211, 2.049)
    move(-1.1,0,0)
    -- return -- return at the end is same as no return, you can remove it
end

script.Parent.ClickDetector.MouseClick:Connect(onClick)

See this for more info on attributes

Ad

Answer this question