Attempt to call nil value on GetTouchingParts?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve?
    I’m making a tycoon game, and I’m working on the pad the parts land on to make money.

  2. What is the issue?
    When a part lands on the pad, I got a “Attempt to call a nil value” error.

  3. What solutions have you tried so far?
    Here’s my script that i attempted.

Parts = {}
function Cash()
	Parts.insert(script.Parent:GetTouchingParts())
	if Parts(1) == "Product" then
		script.Parent.Parent.Counter.SurfaceGui.Money.Value = script.Parent.Parent.Counter.SurfaceGui.Money.Value + 1
	end
end
script.Parent.Touched:Connect(Cash)

GetTouchingParts returns a table.

So how do i assign a table to a table?

try this

Parts = {}
function Cash()
	if script.Parent:GetTouchingParts[1].Name == "Product" then
		script.Parent.Parent.Counter.SurfaceGui.Money.Value = script.Parent.Parent.Counter.SurfaceGui.Money.Value + 1
	end
end
script.Parent.Touched:Connect(Cash)
function Cash()
    for i, Part in pairs(script.Parent:GetTouchingParts()) do
        if Part == "Product" then
            script.Parent.Parent.Counter.SurfaceGui.Money.Value =
                script.Parent.Parent.Counter.SurfaceGui.Money.Value + 1
        end
    end
end
script.Parent.Touched:Connect(Cash)

this wont work because its only checking 1 part

I thought he was only checking the first variable because he used this for the if statement

1 Like

Touched will fire for every part that touches the object. You do not need to store them as a table. Just use the Touched event

while true do
	local part = script.Parent.Touched:Wait() -- Holds the thread until a touch happens
	if (part.Name == "Product") then
		-- Add the money code here
	end
end
2 Likes

I’d argue it’s beneficial to use GetTouchingParts as a fail safe to Touched being as unreliable as everyone knows it is.

This also doesn’t even touch on OP’s original issue - using .insert on the variable instead of using table directly. Same issue is seen in this code:

local parts = {}
parts.insert(1,"hello") --> "attempt to call a nil value"

print(parts[1])

Proper code:

local parts = {}
table.insert(parts,1,"hello")

print(parts[1]) --> "hello"

Using a basic modification of your code though we can implement this fail safe so that no part manages to slip through undetected.

local parts = {}
while true do
	script.Parent.Touched:Wait()
	for _,part in pairs(script.Parent:GetTouchingParts()) do
		if part.Name == "Product" then
			-- give player money
			part:Destroy()
		end
	end
end
1 Like