So I want to make a buy system so when you have enough points you can buy a tool. So I want the part to weld on your hand but I have been struggling with a problem.
items.Parent = character
when I click the buy button this error comes up 'attempt to index nil with ‘Parent’
script.Parent.MouseButton1Click:Connect(function()
local Rep = game:GetService("ReplicatedStorage")
local item = Rep:WaitForChild("Tools")
local items = item:FindFirstChild(script.Parent.Item3.Value)
local price = script.Parent.Parent.Price
local player = script.Parent.Parent.Parent.Parent.Parent.Parent
local stats = player:WaitForChild("leaderstats")
local character = player.Character
if stats.Scoins.Value >= price.Value then
stats.Scoins.Value = stats.Scoins.Value - price.Value
items.Parent = character
items.CFrame = character.RightHand.CFrame
end
end)
I tried to find a solution but I didn’t find a good solution.
This error occurs because item:FindFirstChild(script.Parent.Item3.Value) returns nil. Meaning the :FindFirstChild() function doesn’t find any child of item named the argument you’re providing.
What value type is Item3.Value? :FindFirstChild() requires a string value as its argument. Eventually if the Item3.Value value type is anything other than a string, then you could convert the value into a string by using the tostring(value) function.
The value of items or the Item3’s value is nil or not set.
Also, no need to use :FindFirstChild() unless you want to confirm the existence of something. item[script.Parent.Item3.Value] will work instead except of course you have to fix your nil problem. If it can be nil then you can just check if the value is nil.
EDIT: I made a minor mistake, refer to the reply below me for an alternate possible problem.
It is nil, because :FindFirstChild() tries to find the object in the brackets, but if it isn’t there, it returns nil, which means nothing and you can’t set the parent of nothing, to fix this error, you can check if it is there or it exists, so you can add another statement in the mouseButton1Click event like so:
if stats.Scoins.Value >= price.Value and items then
stats.Scoins.Value = stats.Scoins.Value - price.Value
items.Parent = character
items.CFrame = character.RightHand.CFrame
end
I’m using a string value. So when a click the item icon information is being sent to the info panel including the item name which is the item3 string value. Then when I click to buy it should have received the string value right?