Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Disconnect function not working properly?

local function hitGround(hit)
	print(hit.Name)

	local velocity = Instance.new("BodyVelocity")
	velocity.Name = "BodyVelocity"
	velocity.MaxForce = Vector3.new(4000,4000,4000)
	velocity.Velocity = Vector3.new(0,0,0)
	velocity.Parent = ball
	if hit.Name~= nil then
		connection:Disconnect()
	end
end

local connection = ball.Touched:Connect(hitGround)

This snippet from my code basically connects the hitGround function to the ball.Touched event. However, every time the function is called (which can only be called after the connection object is created), I get the following error:

15:18:25.002 - Workspace.ItemIcons.Blue.Blue.TouchBall.IconScript:19: attempt to index upvalue 'connection' (a nil value)

Since the function cannot be called unless the connection object has been created, why is it still saying that its nil? This doesn't seem to make any sense. Does anyone understand what's going on here? Thanks in advance.

P.S. I have ensured that the function isn't getting called by anything other than the touched event, the error doesnt throw until after hit.Name is printed.

2 answers

✓ Accepted answer

Nevermind, I fixed it, the error was me putting 'local' for both connections.

1 comment

0

mark as answered then

You need to declare connection local before it is first referenced, since a local variable only exists on the lines after it is declared:

local connection
local function hitGround(hit)
    print(hit.Name)

    local velocity = Instance.new("BodyVelocity")
    velocity.Name = "BodyVelocity"
    velocity.MaxForce = Vector3.new(4000,4000,4000)
    velocity.Velocity = Vector3.new(0,0,0)
    velocity.Parent = ball
    if hit.Name~= nil then
        connection:Disconnect()
    end
end

connection = ball.Touched:Connect(hitGround)

This discussion is preserved as it was. New answers, comments, and votes are closed.