Attempt to index nil with 'Disconnect'

I am pretty new to OOP, and i keep giving me an error i have no idea what i am doing wrong to make it occur.

local PartTouched = {}
PartTouched.__index = PartTouched

function PartTouched.new(obj)
	local self = {}
	self.Part = obj
	self.Connection = obj.Touched:Connect(function(hit)
		local Char = hit:FindFirstAncestorWhichIsA("Model")
		if Char then
			local Humanoid = Char:FindFirstChild("Humanoid")
			if Humanoid then
				PartTouched:Ignite()
			end
		end
	end)
	return setmetatable(self, PartTouched)
end

function PartTouched:Ignite()
	print(1)
	self.Connection:Disconnect() -- Location where it occurs.
	self.Part:Destroy()
end

return PartTouched

I would just check if the connection exists.

if self.Connection then
   self.Connection:Disconnect()
end

You should try printing it too just to see if it actually prints nil

if Humanoid then
	PartTouched:Ignite()
end

This just calls the method function PartTouched:Ignite() but self is not passed so Connection will always be nil, since it doesn’t exist.
Iirc, PartTouched.Ignite(self) should work or self:Ignite(), but you should probably set the metatable before calling any of the methods.

1 Like

Thanks for pointing it out.

local PartTouched = {}
PartTouched.__index = PartTouched

function PartTouched.new(obj: Part)
	local self = {}
	setmetatable(self, PartTouched)
	
	self.Part = obj
	self.Connection = obj.Touched:Connect(function(hit)
		local Char = hit:FindFirstAncestorWhichIsA("Model")
		if Char then
			local Humanoid = Char:FindFirstChild("Humanoid")
			if Humanoid then
				self:Ignite()
			end
		end
	end)
end

function PartTouched:Ignite()
	print(1)
	self.Connection:Disconnect()
end

return PartTouched
1 Like

don’t forget to return the newly set metatable!

Oh yeah, my bad I didn’t even realize.

1 Like

Ive added a return self

function PartTouched.new(obj: Part)
	local self = {}
	setmetatable(self, PartTouched)
	
	self.Part = obj
	self.Connection = obj.Touched:Connect(function(hit)
		local Char = hit:FindFirstAncestorWhichIsA("Model")
		if Char then
			local Humanoid = Char:FindFirstChild("Humanoid")
			if Humanoid then
				self:Ignite()
			end
		end
	end)
	return self
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.