Search code examples
luaroblox

Function firing 2000+ times


I'm trying to make an inventory system and now I'm making the equipping system when the player presses the number keys but the code is firing 2000+ times when a number key is pressed.

My code at the moment is:

local player = game.Players.LocalPlayer
local uis = game:GetService("UserInputService")
local inventoryFolder = Instance.new("Folder")
inventoryFolder.Name = "InventoryFolder"
inventoryFolder.Parent = player
local hotbar = script.Parent.Hotbar

for i, v in pairs(player.Backpack:GetChildren()) do
    v.Parent = inventoryFolder
    local slot = hotbar[i]
    if slot.SlotItem.Value == nil then
        slot.SlotItem.Value = v
        slot.Image = game.ReplicatedStorage[tostring(slot.SlotItem.Value)].Texture
    end
end

while wait() do
    uis.InputBegan:Connect(function(key, processed)
        if key.KeyCode == Enum.KeyCode.One then
            print(1)
        end
    end)
end

The key pressed script is only meant to fire once.


Solution

  • while wait() do
        uis.InputBegan:Connect(function(key, processed)
            if key.KeyCode == Enum.KeyCode.One then
                print(1)
            end
        end)
    end
    

    You keep adding callbacks here at roughly 30 callbacks per second. Get rid of the loop.