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 :
01 | local price = script.Parent.Parent.Price |
02 | local tools = game.ReplicatedStorage:WaitForChild( "Tools" ) |
03 | local tool = tools:FindFirstChild(script.Parent.Parent.ItemName.Value) |
04 | local player = game.Players.LocalPlayer |
05 |
06 | script.Parent.MouseButton 1 Click:Connect( function () |
07 | if player.leaderstats:FindFirstChild( "Money" ).Value > = price.Value then |
08 | player.leaderstats:FindFirstChild( "Money" ).Value = player.leaderstats:FindFirstChild( "Money" ).Value - price.Value |
09 | local clone = tool:Clone() |
10 | clone.Parent = player.Backpack |
11 | local clone 2 = tool:Clone() |
12 | clone 2. Parent = player.StarterGear |
13 | end |
14 | 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()
.
01 | local ToolPrice = script.Parent.Parent:WaitForChild( "Price" ) |
02 | local Tools = game.ReplicatedStorage:WaitForChild( "Tools" ) |
03 | local ToolName = script.Parent.Parent:WaitForChild( "ItemName" ) |
04 | local Tool = Tools:WaitForChild(ToolName.Value) |
05 | local Player = game:GetService( "Players" ).LocalPlayer |
06 | local leaderstats = Player:WaitForChild( "leaderstats" ) |
07 | local CurrencyType = "Money" |
08 | local Currency = leaderstats:WaitForChild(CurrencyType) |
09 |
10 | script.Parent.MouseButton 1 Click:Connect( function () |
11 |
12 | if Currency.Value > = ToolPrice.Value then -- Checks if player has right amount |
13 |
14 | Currency.Value = Currency.Value - ToolPrice -- Takes Amount of money after purchased |
15 |
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