0
votes

I recently added some of this code to my Roblox game.

local detector = script.Parent -- Store a reference to the detector.

function onTouch(part) -- The function that runs when the part is touched.
    print('Shop Opened')
    game.StarterGui.ScreenGui.Shop_Background.Visible = true
    game.StarterGui.ScreenGui.Shop.Visible = true

end 

detector.Touched:connect(onTouch) -- The line that connects the function to the event.

Currently, when I load into the game, it prints shop opened usually around 17 times. The GUI opens and it blocks the screen. When I step on the detector it prints 'shop opened' too. If I go into the explorer and make visible equal to false, the box gets unchecked, but the gui still stays there. Is there a way I can fix this?

1
make sure you only execute that function once. either by checking if it has been called yet or by disconnecting the event handler in the first run. I guess you're triggering that touch event multiple times.Piglet

1 Answers

0
votes
local detector = script.Parent -- Store a reference to the detector.
local debounce = false
function onTouch(part) -- The function that runs when the part is touched.
    if not debounce then
    debounce = true
    print('Shop Opened')
    game.StarterGui.ScreenGui.Shop_Background.Visible = true
    game.StarterGui.ScreenGui.Shop.Visible = true

    end
    wait(2) -- Interval until the next execution of if statement
    debounce = false
end 

detector.Touched:connect(onTouch)

You should add debounce to limit the function from running too many times.