Hello, I've been trying to create an inventory system where it will redraw GUI every time the descendants of the inventory folder has been changed. I created a function to do this in a LocalScript called RedrawGrids(), but when I tried to call it using a MouseEnter I receive the following error in the output:
06:02:49.260 - Players.Rheines.PlayerGui.NewInventory.MainFrame.Inventory.Padding.LocalScript:9: attempt to call global 'RedrawGrids' (a nil value)
This is my script:
local PlayerService = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Player = PlayerService.LocalPlayer local Equipped = Player:WaitForChild("Equipped") local Inventory = Player:WaitForChild("Inventory") --Currently use MouseEnter to check if it works. script.Parent.MouseEnter:Connect(RedrawGrids()) --Redraw inventory grids. function RedrawGrids() print('entered function') --Clear all gui to redraw with updated inventory. for _,guis in pairs(script.Parent:GetChildren()) do if guis:IsA("ImageLabel") then guis:Destroy() end end --Redraw inventory contents. for _,gear in pairs(Inventory:GetChildren()) do local gui = ReplicatedStorage.ItemGUI:Clone() gui.Name = gear.Type.Value gui.Parent = script.Parent end end
However, when I made RedrawGrids into an anonymous function such as
script.Parent.MouseEnter:Connect(function() print('entered function') --Clear all gui to redraw with updated inventory. for _,guis in pairs(script.Parent:GetChildren()) do if guis:IsA("ImageLabel") then guis:Destroy() end end --Redraw inventory contents. for _,gear in pairs(Inventory:GetChildren()) do local gui = ReplicatedStorage.ItemGUI:Clone() gui.Name = gear.Type.Value gui.Parent = script.Parent end end)
it works perfectly fine. However, I want to call RedrawGrids as a variable so that I can reuse it as often as I like. Is there something that I did wrong?
:Connect(function())
you need to use :Connect(function)
and you need to put it after function to detect that it is not a nil valueHere is fixed script:
local PlayerService = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Player = PlayerService.LocalPlayer local Equipped = Player:WaitForChild("Equipped") local Inventory = Player:WaitForChild("Inventory") -- Changed location of MouseEnter. --Redraw inventory grids. function RedrawGrids() print('entered function') --Clear all gui to redraw with updated inventory. for _,guis in pairs(script.Parent:GetChildren()) do if guis:IsA("ImageLabel") then guis:Destroy() end end --Redraw inventory contents. for _,gear in pairs(Inventory:GetChildren()) do local gui = ReplicatedStorage.ItemGUI:Clone() gui.Name = gear.Type.Value gui.Parent = script.Parent end end --Currently use MouseEnter to check if it works. script.Parent.MouseEnter:Connect(RedrawGrids) -- removed "()" after "RedrawGrids"
Errors? tell-me on comments.