Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why is my .Changed function still firing?

Asked by 4 years ago

I've created a script that allows me to grab a part. The arm can also be moved used Q and E. When the arm moves, the part that is being grabbed needs to stay updated with the hand but only when "z" is being pressed down (InputBegan). After input has ended the .Changed function (that keeps the part updated) is still fired, even though z is not being pressed and has been disconnected in the InputEnded function. Why is this?

local player = game:GetService('Players').LocalPlayer
local character = script.Parent

local hand1 = character:WaitForChild('Part1')
local hand2 = character:WaitForChild('Part2')
local uis = game:GetService("UserInputService")

local welds = {}
connection = nil
nection = nil

uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.Z then
        connection = hand1.Touched:Connect(function(touching)
                if touching.Name == "Part" then
                    touching.CFrame = hand1.CFrame
                        nection = hand1.Changed:Connect(function()
                            touching.CFrame = hand1.CFrame
                            wait()
                        end)
                welds[#welds + 1] = Instance.new('WeldConstraint')
                welds[#welds].Parent = touching
                welds[#welds].Part0 = touching
                welds[#welds].Part1 = hand1
            end
        end)
    end
end)

uis.InputEnded:Connect(function(input)
    print("work1")
    if input.KeyCode == Enum.KeyCode.Z then
    print("work2")
        if connection then
            connection:Disconnect()
            connection = nil
            print("work3")
        if nection then
            nection:Disconnect()
            nection = nil
            print("work4")
        end
        end
    end

    --// delete all welds
    for i,v in pairs(welds) do
        v:Destroy()
    end
    welds = {}
end)

Answer this question