Door script is not working

  1. Goal When I left click on the knob, CanCollide is turned off & the door is opened. When I left click on it again, CanCollide is back on & the door is closed.

The click detector is working alongside the door opened, just the closing door is not working.

Script:

-- variables 
local knob = script.Parent
local door = game.Workspace.Door
local CursorID = "2287179355"

local dooropen = false


-- Create ClickDetector
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = knob
ClickDetector.MaxActivationDistance = 10
ClickDetector.CursorIcon = "rbxassetid://"..CursorID

-- make door slightly transparent when mouse hovers
 ClickDetector.MouseHoverEnter:Connect(function() 
	door.Transparency = 0.1
	knob.Transparency = 0.1
end)

-- door is not transparent when mouse isnt overit
ClickDetector.MouseHoverLeave:Connect(function()
	door.Transparency = 0
	knob.Transparency = 0
end)

-- open door on left mouse click
ClickDetector.MouseClick:Connect(function()
	door.Transparency = 0.3
	door.CanCollide = false
	knob.Transparency = 0.3
	knob.CanCollide = false
	dooropen = true
end)

-- if clicked again, door closes

if dooropen == true then
	ClickDetector.MouseClick:Connect(function()
		door.Transparency = 0
		door.CanCollide = true
		knob.Transparency = 0
		knob.CanCollide = true
		dooropen = false
	end)
end

Everything is working except for the close door, which is the last script.

Thanks!

try this:

local knob = script.Parent
local door = game.Workspace.Door
local CursorID = "2287179355"

local dooropen = false


-- Create ClickDetector
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = knob
ClickDetector.MaxActivationDistance = 10
ClickDetector.CursorIcon = "rbxassetid://"..CursorID

-- make door slightly transparent when mouse hovers
ClickDetector.MouseHoverEnter:Connect(function() 
	door.Transparency = 0.1
	knob.Transparency = 0.1
end)

-- door is not transparent when mouse isnt overit
ClickDetector.MouseHoverLeave:Connect(function()
	door.Transparency = 0
	knob.Transparency = 0
end)

-- open/close door on left mouse click
ClickDetector.MouseClick:Connect(function()
	if not dooropen then
		door.Transparency = 0.3
		door.CanCollide = false
		knob.Transparency = 0.3
		knob.CanCollide = false
		dooropen = true
	elseif dooropen then
		door.Transparency = 0
		door.CanCollide = true
		knob.Transparency = 0
		knob.CanCollide = true
		dooropen = false
	end
end)

The issue was the if statement was around the event, it should be the other way around, the event around the if statement.
Also you can put both the if dooropen and if dooropen not open in the same mouse clicked event,