Variable not updating in function call

The problem is, that when i touch a part, that part should change. But this doesn’t happen. When i print out the variable that i have to touch, it prints the right thing.

local ToTouch = workspace.PartA

local function FunctionA()
	print(ToTouch.Name) --This prints "Part A" for the first time, then "part B" for the second time
	ToTouch = workspace.PartB
end

ToTouch.Touched:Connect(FunctionA) --only fires when part A is touched

External Media

Your function is connected to what “ToTouch” is the first time. Even when you change the variable it still is connected to the same original instance. You will have to reconnect the event

Any idea on how should i do that?

local ToTouch = workspace.PartA

local activeConnection

local function FunctionA()
	print(ToTouch.Name)
	ToTouch = workspace.PartB
        activeConnection:Disconnect()

       activeConnection = ToTouch.Touched:Connect(FunctionA)

end

activeConnection = ToTouch.Touched:Connect(FunctionA)

Though this is a odd behavior your trying to create

1 Like

Thanks for the help! It worked

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