Hello, I made a function that automatically snaps a part to the bottom whenever its moved. I want it to stop doing this when the LockToBottom variable is set to false.
Here is my code:
local function Lock(part)
local event = part:GetPropertyChangedSignal("Position"):Connect(function()
if LockToBottom then
local OldPos = part:GetPivot().Position
local Bk = game.Workspace.buildKit.walls.Bottom
part:PivotTo(CFrame.new(Vector3.new(OldPos.X, Bk.Position.Y + Bk.Size.Y ,OldPos.Z)))
else
event:Disconnect()
end
end)
end
it errors on event:Disconnect:
unknown global 'event'
How would I disconnect the event so that it doesnt play multiple times if the variable is ticked multiple times?
Disconnecting a function means that you’ll no longer need it after checking your conditional statements, you’ll have to change up your script a bit if you want the event to be able to properly detect when to disconnect it
Assuming from your scenario here, what you’ll have to do is create a Connection outside the scope of your Lock function, and call the function by connecting it like so here:
We’ll also have to redo our Lock function a bit, along with adding a couple more variables here:
local Connection
local LockToBottom -- Whatever it is
local function Lock(part)
if LockToBottom then
local OldPos = part:GetPivot().Position
local Bk = game.Workspace.buildKit.walls.Bottom
part:PivotTo(CFrame.new(Vector3.new(OldPos.X, Bk.Position.Y + Bk.Size.Y ,OldPos.Z)))
else
Connection:Disconnect()
end
end
Connection = PartInstance:GetPropertyChangedSignal("Position"):Connect(function()
Lock(PartInstance)
end)
PartInstance is obviously your current Part that you want to pass through the function here, and LockToBottom is the same thing, just define it how you originally did
What’s different about this, is that we’re handling our Connection outside our function so we’re able to access it globally (Anywhere within this script), and we want that as we would need to Connect/Disconnect our Events whenever we have to define them rather than keeping it inside our function as local variable, and once LockToBottom is valid then we then stop listening for changes for that Connection :L
You can learn more about how to Disconnect Events here, as there’s a whole guide that explains the process about it
local function Lock(part)
local event = nil
event = part:GetPropertyChangedSignal("Position"):Connect(function()
if LockToBottom then
local OldPos = part:GetPivot().Position
local Bk = workspace.buildKit.walls.Bottom
part:PivotTo(CFrame.new(Vector3.new(OldPos.X, Bk.Position.Y + Bk.Size.Y, OldPos.Z)))
else
event:Disconnect()
end
end)
end