Im working on a shop GUI and im just one error away from completing it. it keeps saying "attempt to index upvalue 'tool' (a nil value)". How do I fix it? here's my script attempt :
local price = script.Parent.Parent.Price local tools = game.ReplicatedStorage:WaitForChild("Tools") local tool = tools:FindFirstChild(script.Parent.Parent.ItemName.Value) local player = game.Players.LocalPlayer script.Parent.MouseButton1Click:Connect(function() if player.leaderstats:FindFirstChild("Money").Value >= price.Value then player.leaderstats:FindFirstChild("Money").Value = player.leaderstats:FindFirstChild("Money").Value - price.Value local clone = tool:Clone() clone.Parent = player.Backpack local clone2 = tool:Clone() clone2.Parent = player.StarterGear end end)
The reason why you get the error: Attempt to index upvalue 'tool' (A nil value)
is to cause the way to that Tool isn't correct. In this case, I can only short your code and make it easier to understand. I prefer using :WaitForChild()
cause it waits for something to be loaded, in your case you should be using it, that may be the reason why the script didn't work. As I see, you used :FindFirstChild()
well, you should not be using it cause it searches for the part even before the part is loaded or tool, so you should be using :WaitForChild()
.
local ToolPrice = script.Parent.Parent:WaitForChild("Price") local Tools = game.ReplicatedStorage:WaitForChild("Tools") local ToolName = script.Parent.Parent:WaitForChild("ItemName") local Tool = Tools:WaitForChild(ToolName.Value) local Player = game:GetService("Players").LocalPlayer local leaderstats = Player:WaitForChild("leaderstats") local CurrencyType = "Money" local Currency = leaderstats:WaitForChild(CurrencyType) script.Parent.MouseButton1Click:Connect(function() if Currency.Value >= ToolPrice.Value then -- Checks if player has right amount Currency.Value = Currency.Value - ToolPrice -- Takes Amount of money after purchased local clone = tool:Clone() clone.Parent = player.Backpack local clone2 = tool:Clone() clone2.Parent = player.StarterGear else -- code here end end)
Actually why its not working is because its not FE. With latest Roblox update you need to make it FE compatible. And you should use RemoteEvent and RemoteFunctions. If you dont know what is FE, then you should read these pages first.
https://wiki.roblox.com/index.php?title=API:Class/Workspace/FilteringEnabled
https://wiki.roblox.com/index.php?title=API:Class/RemoteEvent
https://wiki.roblox.com/index.php?title=API:Class/RemoteFunction